How to properly check if PHP is configured correctly to use DOMDocument?
P粉898049562
2023-07-30 17:50:54
<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>
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:
or:
Of course, you can directly use extension_loaded('dom') to detect whether the extension is available.
You can use the class_exists() function to test whether a class exists. For example: