How to properly check if PHP is configured correctly to use DOMDocument?
P粉898049562
P粉898049562 2023-07-30 17:50:54
0
2
473
<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粉898049562
P粉898049562

reply all(2)
P粉973899567

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.

P粉546257913

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


if (!class_exists('DOMDocument')){
   echo "Please install DOMDocument";
   exit;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!