The PHP XML Parser is a thin wrapper around Expat, a fast, event-driven XML parser written in C. You do not ask it for a tree. Instead you give it your own functions, called handlers, and it calls them while it reads the document from the first byte to the last: once for each opening tag, once for each piece of text, and once for each closing tag.
When you only need the data and not the streaming, xml_parse_into_struct() reads the whole document and returns it as two plain arrays, with no handlers to write.
Use handlers for large files or when you want to stop early. Use xml_parse_into_struct() for small documents you want as an array. If you want to walk a document as objects, SimpleXML or DOM is usually easier than this extension.
Event-driven means no tree.
Expat forgets each element as soon as it has called your handlers. If you need the parent of a tag, or the text of a whole element, keep that state yourself, for example in a stack or in a variable the handlers share.
Syntax
PHP Syntax
The usual pattern: create a parser, register handlers, parse, and check the result:
PHP
// XMLParser object (PHP 8): the parser you will configure
$parser = xml_parser_create();
// Handlers: called while the document is read
xml_set_element_handler($parser, 'onStart', 'onEnd');
xml_set_character_data_handler($parser, 'onText');
function onStart($parser, string $name, array $attrs) { /* opening tag */ }
function onEnd($parser, string $name) { /* closing tag */ }
function onText($parser, string $data) { /* text between tags */ }
// int: 1 on success, 0 on failure; true marks the final chunk
$ok = xml_parse($parser, $xml, true);
if (!$ok) {
$code = xml_get_error_code($parser); // int
echo xml_error_string($code); // string, e.g. Mismatched tag
echo xml_get_current_line_number($parser); // int
}
// No handlers: whole document as arrays (use a fresh parser)
$p2 = xml_parser_create();
xml_parse_into_struct($p2, $xml, $values, $index);
Reference
Core Ideas
What to remember when you work with the XML parser:
Before PHP 8.0 the parser was a resource. From PHP 8.0 on, xml_parser_create() returns an instance of the final class XMLParser. The functions work the same way; the differences are small but worth knowing:
Topic
PHP 7 and earlier
PHP 8
Parser type
A resource; test it with is_resource()
An XMLParser object; test it with instanceof XMLParser
The object is freed when it goes out of scope; xml_parser_free() is a no-op (deprecated in PHP 8.5)
Copying
Copying a resource shares the same parser
An XMLParser cannot be cloned or serialized
Namespaces with xml_parser_create_ns()
A plain parser treats dc:title as one name that happens to contain a colon. xml_parser_create_ns() understands namespaces. It takes an optional encoding and a separator character, and it gives your handlers names in the form namespace-URI + separator + local-name:
PHP
// separator "|" keeps the URI easy to split
$parser = xml_parser_create_ns('UTF-8', '|');
// keep the original case, XML names are case sensitive
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
// Handlers receive names like "http://example.com/ns|item"
xml_set_element_handler($parser, 'onStart', 'onEnd');
// Optional: be told when a prefix is declared or goes out of scope
xml_set_start_namespace_decl_handler($parser, 'onPrefixStart');
xml_set_end_namespace_decl_handler($parser, 'onPrefixEnd');
Turn off case folding for namespaces.
With folding on, the whole name is upper-cased, including the URI, so you can no longer compare it with the real namespace string. Set XML_OPTION_CASE_FOLDING to 0 before you parse.
Code
PHP Examples
Three short scripts that show how the XML parser works. Each one parses a tiny XML string written in the script itself, so the output is the same every time you run it.
Example 1 — Element and character data handlers
Parse a small <book> document and print each event as the parser meets it.
Start: BOOK (ID=7)
Start: TITLE
Text: Learn PHP
End: TITLE
Start: YEAR
Text: 2024
End: YEAR
End: BOOK
How It Works
xml_parser_create() returns the parser. Nothing is read yet; it only waits for handlers and data.
xml_set_element_handler() takes two callables. The start handler gets the tag name and an array of attributes, and the end handler gets only the tag name. Closures work as well as function names.
Case folding is on by default, so book, title and the attribute id reach the handlers as BOOK, TITLE and ID.
xml_parse($parser, $xml, true) reads the whole string. The true says this is the final chunk. The text handler runs for Learn PHP and 2024, between the matching start and end events.
Example 2 — xml_get_error_code() and xml_error_string()
Parse a document with a mismatched closing tag on line 3, then ask the parser what went wrong and where.
Parse failed
Code: 7
Message: Mismatched tag
Line: 3
Is mismatch: yes
How It Works
The second <item> is closed with </oops>, so the document is not well formed. xml_parse() stops and returns 0, which makes the if block run.
xml_get_error_code() returns the number of the error. Here it is 7, the value of the constant XML_ERROR_TAG_MISMATCH.
xml_error_string() turns that number into readable text: Mismatched tag.
xml_get_current_line_number() reports line 3, where the bad tag is. Use xml_get_current_column_number() as well when you want to show the exact spot to a user.
Example 3 — xml_parse_into_struct() as an alternative
Read a short list into arrays with no handlers, then print each entry and the positions of the ITEM tags.
open LIST level=1 id=- value=
complete ITEM level=2 id=1 value=Apple
complete ITEM level=2 id=2 value=Pear
close LIST level=1 id=- value=
ITEM positions: 1,2
How It Works
xml_parse_into_struct() parses the whole string and fills $values and $index. No handlers are needed.
Each entry in $values has a tag, a type (open, complete, close, or cdata) and a level for the depth. Entries with text or attributes also carry value and attributes.
An element that holds only text, like <item> here, becomes a single complete entry. <list> has children, so it gets an open entry and a close entry.
$index maps each tag name to the positions of its entries in $values. ITEM sits at positions 1 and 2, so you can jump straight to the items.
The trade-off: the whole result lives in memory. For a large file, stay with handlers.
Continue
Next: PHP XML Parser Functions Index
After you know handlers, errors, and the struct alternative, open the functions index for all 22 guides.
It is a set of xml_* functions that wrap the Expat library. Expat is an event-driven (SAX-style) parser: it reads the document from start to end and calls your functions when it meets an opening tag, text, or a closing tag. It never builds a tree in memory, so it can read very large files with a small, steady memory use.
With handlers you register functions through xml_set_element_handler() and xml_set_character_data_handler(), and PHP calls them as the document is read. With xml_parse_into_struct() PHP reads the whole document and gives you two arrays, a flat list of values and an index of tag names. Handlers use less memory and give you full control; the struct is shorter to write for small documents.
Case folding is on by default, so element and attribute names are passed to your handlers in upper case. Turn it off with xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0) before you call xml_parse(). XML itself is case sensitive, so turning folding off is usually the safer choice.
xml_parse() returns 0 on failure. Pass xml_get_error_code($parser) to xml_error_string() to get a message such as Mismatched tag, and use xml_get_current_line_number() and xml_get_current_column_number() to point at the place in the document. Read these values before you free the parser or parse more data.
Create the parser with xml_parser_create_ns($encoding, $separator). Element and attribute names then reach your handlers as the namespace URI, the separator, and the local name, for example http://example.com/ns:item. Register xml_set_start_namespace_decl_handler() if you also want to know when a prefix is declared.
No. Since PHP 8.0 xml_parser_create() returns an XMLParser object instead of a resource, and the object is freed when it goes out of scope. xml_parser_free() still exists but does nothing useful on PHP 8, and it is deprecated as of PHP 8.5, so you can leave it out.