'PHP 8 - libxml_disable_entity_loader() has been deprecated. How do I replace the functionality it provides?
I am upgrading to PHP 8 and getting the following warning:
Function libxml_disable_entity_loader() is deprecated
What I have: This code saves the current entity loader status, and enables the loader; then loads the file; and finally resets the entity loader to its original status:
...
$current = libxml_disable_entity_loader(false);
$domdocument->load($filename,$options);
libxml_disable_entity_loader($current);
...
I read the following regarding PHP 8:
as of libxml 2.9.0 entity substitution is disabled by default, so there is no need to disable the loading of external entities, unless there is the need to resolve internal entity references with LIBXML_NOENT.
To test, I removed the libxml_disable_entity_loader() references, thus What I have: becomes:
...
$domdocument->load($filename,$options);
...
However, now of course I get:
PHP Warning: DOMDocument::load(): I/O warning : failed to load external entity
So, my question is:
What do I need to do in PHP 8 to get rid of libxml_disable_entity_loader() and still achieve the equivalent of What I have:
Solution 1:[1]
I have not dug deep into this topic, but I suppressed the warning by adding @ symbol at the beginning of the method and no change has come to the result of the code. try like below
...
$current = @libxml_disable_entity_loader(false);
$domdocument->load($filename,$options);
@libxml_disable_entity_loader($current);
...
Solution 2:[2]
I can't speak for all use cases but in mine all loads are from local files, so I have resolved the problem by replacing ->load() with a combination of file_get_contents() and ->loadXML() as follows:
...
$domdocument->loadXML(file_get_contents($filename),$options);
...
Thus side stepping the "external" consideration.
Solution 3:[3]
If you really need to keep support for external entities you can use the mentioned LIBXML_NOENT
flag to do so. Just add it to $options
to pass it to DOMDocument::load()
.
$options = $options | LIBXML_NOENT;
$domdocument->load($filename,$options);
As described in the documentation for DOMDocument::load()
, the $options
parameter is there to pass:
Bitwise OR of the libxml option constants
Please note that it's not advised to use LIBXML_NOENT
unless you can absolutely trust the XML source as it opens you up for XML External Entity (XXE) Processing attacks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Pancho |
Solution 3 | Michael D. |