Skip to content

xml_set_unparsed_entity_decl_handler()

The xml_set_unparsed_entity_decl_handler() function is a PHP built-in function that sets a user-defined callback as the handler for unparsed entity declarations in an XML parser. It belongs to the XML Parser extension and works exclusively with the SAX-style parser, not with SimpleXML. This handler is useful when you need to process unparsed entities (such as binary data like images or PDFs referenced in XML) without loading them into memory.

Syntax

The syntax of the xml_set_unparsed_entity_decl_handler() function is as follows:

syntax of the xml_set_unparsed_entity_decl_handler() function in PHP

php
xml_set_unparsed_entity_decl_handler($parser, $handler)

Where $parser is the XML parser resource on which the handler is set, and $handler is the name of the user-defined callback function that will handle unparsed entity declarations.

Usage Examples

Let's take a look at a practical example of using xml_set_unparsed_entity_decl_handler() in PHP.

Example: Setting an Unparsed Entity Declaration Handler Function

Suppose you have an XML document containing an unparsed entity declaration. You can use the xml_parser_create() function to create a new SAX parser, set the handler using xml_set_unparsed_entity_decl_handler(), and then parse the XML data:

Setting an Unparsed Entity Declaration Handler Function in PHP

php
function handle_unparsed_entity($parser, $name, $base, $systemId, $publicId, $notationName) {
    echo "Unparsed entity '$name' found: $systemId (notation: $notationName)\n";
}

$xml_parser = xml_parser_create();
xml_set_unparsed_entity_decl_handler($xml_parser, "handle_unparsed_entity");

$xml_data = '<?xml version="1.0"?>
<!DOCTYPE root [
  <!ENTITY logo SYSTEM "logo.png" NDATA png>
]>
<root/>';

xml_parse($xml_parser, $xml_data, true);
xml_parser_free($xml_parser);

This code creates a new SAX parser using xml_parser_create(). It then registers the handle_unparsed_entity() callback to process unparsed entity declarations. When xml_parse() processes the XML string, the callback executes and outputs the entity details. You can modify the callback to extract specific information or perform any other necessary actions.

Conclusion

In this article, we've discussed PHP's xml_set_unparsed_entity_decl_handler() function and how it integrates with the SAX-style XML parser. We've explained what unparsed entities are, reviewed the function's syntax, and provided a complete, runnable example. By using this handler in your PHP applications, you can efficiently process binary data references in XML without loading them into memory.

Practice

What is the function of the xml_set_unparsed_entity_decl_handler function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.