skip to Main Content

I have a script that uses DOMDocument. In some environments, it fails, presumably due to some module is not loaded. What I’m trying to do is to provide a user of this script instructions to fix this behavior.

Here’s a minimal script to reproduce the problem:

<?php
  echo 'start!';
  try {
    $doc = new DOMDocument();
  } catch (Exception $e) {
    echo 'catched';
  }
  echo 'end';
?>

If I open it in browser (served by my current server, involving Nginx), I see just start! (and the return code is 500; same output if I omit try..catch). So the problem is not only in detecting whether the right module is installed (should I use extension_loaded('dom') to check it?), but also the fact that try..catch doesn’t seem to work (I don’t get catched in the output; I’m using PHP 7.4.3 in the current case).

Any suggestions of how should I process this case correctly?

3

Answers


  1. You can test for the class with class_exists()

    Eg

    if (!class_exists('DOMDocument')){
       echo "Please install DOMDocument";
       exit;
    }
    
    Login or Signup to reply.
  2. When a class is not found, an Error is raised. That class does not extend Exception, which is why your code doesn’t catch it.

    This will work:

    try
    {
        new DOMDocument();
    }
    catch(Error $e)
    {
        echo 'DOMDocument not available';
    }
    

    Or:

    try
    {
        new DOMDocument();
    }
    catch(Throwable $t)
    {
        echo 'DOMDocument not available';
    }
    

    Of course, you can directly test extension_loaded('dom') to detect if the extension is available.

    Login or Signup to reply.
  3. if(!extension_loaded("xml")){
        throw new Error("required extension libxml is not installed ( https://www.php.net/manual/en/libxml.installation.php )");
    }
    

    also the fact that try..catch doesn’t seem to work (I don’t get catched in the output; I’m using PHP 7.4.3 in the current case).

    as of PHP7, when a class cannot be found, it throws an Error, which is not a descendant of Exception (because the PHP designers got it wrong), so your (Exception $e) doesn’t qualify. To catch anything thrown, use catch (Throwable $e) (fwiw both Error and Exception are descendant of Throwable)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search