PHP xml_set_start_namespace_decl_handler() Function
Beginner
5 min read
Updated: Nov 2026
3 examples
XML Parser
Definition
In PHP, xml_set_start_namespace_decl_handler() registers the function that runs when an XML namespace declaration comes into scope.
A declaration such as xmlns:a="urn:a" connects the prefix a with the namespace URI urn:a. The parser calls your handler with both values just before it reports the element that contains the declaration. It only works with a parser created by xml_parser_create_ns().
Syntax
Call xml_set_start_namespace_decl_handler() with the values you need. Start with this line.
Your handler is called as handler(XMLParser $parser, string|false $prefix, string $uri). The prefix is false for a default namespace such as xmlns="urn:feed". This is a niche handler, and everyday XML apps mainly need the element handler and the character data handler.
The helper registers the handler on whichever parser it receives and counts the calls.
A parser from xml_parser_create() does not process namespaces, so xmlns is just an attribute and the count stays 0.
A parser from xml_parser_create_ns() recognizes the declaration and calls the handler once.
The two printed lines show why namespace handlers need xml_parser_create_ns().
Frequently Asked Questions
It sets the function the parser calls when a namespace declaration, such as xmlns:a="urn:a", comes into scope. The function receives the prefix and the URI.
The parser must come from xml_parser_create_ns(). A parser from xml_parser_create() does not process namespaces and ignores the handler.
The prefix is false when the declaration has no prefix, such as xmlns="urn:feed". Check it with === false before using it as a string.
The namespace handler runs just before the start element handler of the element that holds the declaration, so your code knows the prefix before the tag arrives.
Usually not. Most scripts only need xml_set_element_handler() and xml_set_character_data_handler(). Namespace handlers are for tools that track prefixes and URIs.