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.
Here is a minimal script to reproduce the issue:
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).
Do you have any suggestions on how to properly handle this situation?
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: