PHP XML Parser

Beginner
9 min read
Updated: Nov 2026
3 examples
Handlers, errors & structs

Definition and Usage

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.

The usual flow has four steps. Create a parser with xml_parser_create(). Register handlers with xml_set_element_handler() and xml_set_character_data_handler(). Feed the XML to xml_parse(). If it fails, ask the parser what went wrong with xml_get_error_code() and xml_error_string().

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.

This page explains the ideas. The XML Parser Functions index lists all 22 function guides.

Pick the right tool.

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.

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);

Core Ideas

What to remember when you work with the XML parser:

IdeaFunctionRemember
Create a parserxml_parser_create()Returns an XMLParser object in PHP 8; the optional argument is the output encoding, UTF-8 by default
Element handlersxml_set_element_handler()Takes a start handler ($parser, $name, $attrs) and an end handler ($parser, $name); names are upper case unless you turn folding off
Text handlerxml_set_character_data_handler()May be called more than once for one run of text, so join the pieces yourself
Parsexml_parse()Pass the data and true for the last chunk; you can call it many times with pieces of a big file
Errorsxml_get_error_code() / xml_error_string()Get the code first, then turn it into text; XML_ERROR_* constants name the codes
Positionxml_get_current_line_number() / xml_get_current_column_number() / xml_get_current_byte_index()Lines start at 1, columns and byte indexes start at 0; call them inside a handler or right after a failed parse
Optionsxml_parser_set_option() / xml_parser_get_option()Case folding, target encoding, skipping white space, and skipping a tag prefix; set them before you parse
Array outputxml_parse_into_struct()Fills a flat $values list and a $index map of tag names to positions

Other handlers you can register

Besides elements and text, Expat can report everything else in a document. xml_set_default_handler() receives any data that has no other handler. xml_set_processing_instruction_handler() receives <?target data?> lines, and xml_set_external_entity_ref_handler(), xml_set_notation_decl_handler() and xml_set_unparsed_entity_decl_handler() cover entities and notations. To use methods of an object as handlers, pass [$object, 'method']; the older xml_set_object() does the same job and is deprecated in PHP 8.4.

PHP 8 XMLParser Object and Namespaces

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:

TopicPHP 7 and earlierPHP 8
Parser typeA resource; test it with is_resource()An XMLParser object; test it with instanceof XMLParser
FreeingCall xml_parser_free() to release itThe object is freed when it goes out of scope; xml_parser_free() is a no-op (deprecated in PHP 8.5)
CopyingCopying a resource shares the same parserAn 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.

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.

PHP
<?php
$xml = '<book id="7"><title>Learn PHP</title><year>2024</year></book>';

$parser = xml_parser_create();

xml_set_element_handler(
    $parser,
    function ($p, $name, $attrs) {
        $list = [];
        foreach ($attrs as $key => $value) {
            $list[] = "$key=$value";
        }
        echo "Start: $name", $list ? ' (' . implode(', ', $list) . ')' : '', PHP_EOL;
    },
    function ($p, $name) {
        echo "End: $name", PHP_EOL;
    }
);

xml_set_character_data_handler($parser, function ($p, $data) {
    echo "Text: $data", PHP_EOL;
});

xml_parse($parser, $xml, true);
?>

How It Works

  1. xml_parser_create() returns the parser. Nothing is read yet; it only waits for handlers and data.
  2. 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.
  3. Case folding is on by default, so book, title and the attribute id reach the handlers as BOOK, TITLE and ID.
  4. 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.

PHP
<?php
$xml = "<root>\n<item>One</item>\n<item>Two</oops>\n</root>";

$parser = xml_parser_create();

if (!xml_parse($parser, $xml, true)) {
    $code = xml_get_error_code($parser);

    echo "Parse failed", PHP_EOL;
    echo "Code: ", $code, PHP_EOL;
    echo "Message: ", xml_error_string($code), PHP_EOL;
    echo "Line: ", xml_get_current_line_number($parser), PHP_EOL;
    echo "Is mismatch: ", $code === XML_ERROR_TAG_MISMATCH ? 'yes' : 'no', PHP_EOL;
}
?>

How It Works

  1. 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.
  2. xml_get_error_code() returns the number of the error. Here it is 7, the value of the constant XML_ERROR_TAG_MISMATCH.
  3. xml_error_string() turns that number into readable text: Mismatched tag.
  4. 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.

PHP
<?php
$xml = '<list><item id="1">Apple</item><item id="2">Pear</item></list>';

$parser = xml_parser_create();
xml_parse_into_struct($parser, $xml, $values, $index);

foreach ($values as $v) {
    $id = $v['attributes']['ID'] ?? '-';
    $text = $v['value'] ?? '';
    echo $v['type'], ' ', $v['tag'], ' level=', $v['level'], ' id=', $id, ' value=', $text, PHP_EOL;
}

echo 'ITEM positions: ', implode(',', $index['ITEM']), PHP_EOL;
?>

How It Works

  1. xml_parse_into_struct() parses the whole string and fills $values and $index. No handlers are needed.
  2. 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.
  3. 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.
  4. $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.
  5. The trade-off: the whole result lives in memory. For a large file, stay with handlers.

Next: PHP XML Parser Functions Index

After you know handlers, errors, and the struct alternative, open the functions index for all 22 guides.

Start withWhy
xml_parser_create()Create the parser object and choose the output encoding
xml_set_element_handler()Run your code for every opening and closing tag
xml_set_character_data_handler()Receive the text between tags
xml_parse()Feed XML to the parser in one piece or in chunks
xml_error_string()Turn an error code into a readable message
xml_parse_into_struct()Get a document as arrays instead of writing handlers
xml_parser_create_ns()Parse documents that use XML namespaces

Full list: PHP XML Parser Functions index (/php/xml-parser/function).

Frequently Asked Questions

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.

Browse every XML Parser function

Open the functions index for categorized guides with examples and FAQs.

XML Parser Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful