Function xml_parser_free is Deprecated in PHP 8.5

Function xml_parser_free is Deprecated in PHP 8.5

PHP provides a built-in XML parser extension that allows developers to process XML documents using event-based callbacks. Before PHP 8.0, XML parser was represented as a resource, and the xml_parser_free function was required to explicitly release the memory associated with a parser once it was no longer needed. Since PHP 8.0, this internal behavior changed. XML parser is now represented by the XMLParser object rather than a resource. Because of this change, the parser is automatically cleaned up when there are no remaining references or when explicitly destroyed.

Since PHP 8.5, the xml_parser_free function triggers a deprecation warning:

<?php

$xml = '<hello>World</hello>';

$parser = xml_parser_create();
xml_set_character_data_handler($parser, function (XMLParser $parser, string $data) {
    echo $data; // World
});
xml_parse($parser, $xml, true);
xml_parser_free($parser);

Example will output:

Deprecated: Function xml_parser_free() is deprecated since 8.5, as it has no effect since PHP 8.0 in ...

To eliminate the deprecation warning, simply remove the call to xml_parser_free. The XMLParser object will be released automatically when it goes out of scope. Alternatively, the parser can be released manually by calling unset($parser) or by setting $parser = null.

<?php

$xml = '<hello>World</hello>';

$parser = xml_parser_create();
xml_set_character_data_handler($parser, function (XMLParser $parser, string $data) {
    echo $data; // World
});
xml_parse($parser, $xml, true);
unset($parser);

Leave a Comment

Cancel reply

Your email address will not be published.