Home  >  Q&A  >  body text

How to properly check if PHP is configured correctly to use DOMDocument?

<p>I have a script that uses DOMDocument. In some environments it fails, possibly because a module is not loaded. What I want to do is provide guidance on fixing this issue for users of this script. </p><p>Here is a minimal script to reproduce the issue: </p><p><br /></p> <pre class="brush:php;toolbar:false;"><?php echo 'start!'; try { $doc = new DOMDocument(); } catch (Exception $e) { echo 'catched'; } echo 'end'; ?></pre> <p> If I open it in a browser (served by my current server, involving Nginx), I only see "start!" (return code 500; if I omit try..catch, the output is the same). So the problem is not only detecting whether the correct module is installed (should I use extension_loaded('dom') to check?), but also that try..catch doesn't seem to work (I don't get caught in the output; in the current case , I'm using PHP 7.4.3). <br /><br />Do you have any suggestions on how to properly handle this situation? </p><p><br /></p>
P粉898049562P粉898049562470 days ago478

reply all(2)I'll reply

  • P粉973899567

    P粉9738995672023-07-31 16:50:19

    When a class is not found, an error is raised. This class does not inherit Exception, so your code cannot catch it.

    The following code can solve this problem:


    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 use extension_loaded('dom') to detect whether the extension is available.

    reply
    0
  • P粉546257913

    P粉5462579132023-07-31 16:03:24

    You can use the class_exists() function to test whether a class exists. For example:


    if (!class_exists('DOMDocument')){
       echo "Please install DOMDocument";
       exit;
    }

    reply
    0
  • Cancelreply