W3docs

xml_parser_create()

The xml_parser_create() function is a PHP built-in function that creates a new XML parser. When parsing XML files using the SimpleXML library or other XML

The xml_parser_create() function is a PHP built-in function that creates a new XML parser. It belongs to the legacy xml (Expat) extension and is used for SAX-style (event-driven) parsing. Unlike higher-level extensions such as SimpleXML or DOMDocument, this parser processes XML data sequentially by triggering user-defined callback functions for elements, attributes, and character data.

The xml_parser_create() function is useful when you need to stream-parse large XML files, extract specific data without loading the entire document into memory, or process XML in a low-level, event-driven manner.

The function returns an XML parser you store in a variable and pass to every other xml_* function. As of PHP 8.0 it returns an XMLParser object; in earlier versions it returned a resource. Either way you treat it as an opaque handle — set handlers on it, feed it data with xml_parse(), then release it with xml_parser_free().

Syntax

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

syntax of the xml_parser_create() function

xml_parser_create([$encoding])

Where $encoding is the character encoding used by the XML data (for example "UTF-8", "ISO-8859-1", or "US-ASCII"). This parameter is optional; when omitted, the parser detects the encoding from the document's XML declaration.

Usage Examples

Let's take a look at some practical examples of using xml_parser_create() in PHP.

Example 1: Creating an XML Parser

You can use the xml_parser_create() function to initialize a parser resource. Note that creating the parser alone does not process any data; you must configure handlers and call xml_parse() to actually parse XML.

use the xml_parser_create() function to create a new XML parser in PHP

$xml_parser = xml_parser_create();

This code creates a new XML parser resource. By itself, it is just an empty container ready to be configured.

Example 2: Parsing XML Data

To actually parse XML, you need to set up event handlers and feed data to the parser using xml_parse().

use the xml_parser_create() function to parse XML data in PHP

$xml_parser = xml_parser_create();
$xml_data = file_get_contents("data.xml");

// Set up element handlers
xml_set_element_handler($xml_parser, function($parser, $name) {
    echo "Start element: $name\n";
}, function($parser, $name) {
    echo "End element: $name\n";
});

// Parse the data
if (!xml_parse($xml_parser, $xml_data, true)) {
    die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($xml_parser)),
        xml_get_current_line_number($xml_parser)));
}
xml_parser_free($xml_parser);

This code creates a parser, registers callbacks for opening and closing tags, and uses xml_parse() to process the XML file. The parser triggers the callbacks as it reads the data sequentially.

Example 3: Extracting Data from Inline XML

This self-contained example parses an XML string and collects each element's text into an array using a character-data handler. It runs as-is, without any external file.

extract data from XML using the xml extension in PHP

$xml_data = <<<XML
<?xml version="1.0"?>
<book>
    <title>Learn PHP</title>
    <author>W3docs</author>
</book>
XML;

$xml_parser = xml_parser_create();
$current_tag = '';
$book = [];

xml_set_element_handler(
    $xml_parser,
    function ($parser, $name) use (&$current_tag) {
        $current_tag = $name; // element names arrive UPPERCASE by default
    },
    function ($parser, $name) use (&$current_tag) {
        $current_tag = '';
    }
);

xml_set_character_data_handler(
    $xml_parser,
    function ($parser, $data) use (&$current_tag, &$book) {
        $data = trim($data);
        if ($current_tag !== '' && $data !== '') {
            $book[$current_tag] = $data;
        }
    }
);

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

print_r($book);

Output:

Array
(
    [TITLE] => Learn PHP
    [AUTHOR] => W3docs
)

Notice the keys are uppercase. By default the Expat parser folds element names to uppercase, which is why the handler stores TITLE and AUTHOR rather than title and author. To keep the original case, turn off case folding right after creating the parser:

xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);

The character-data handler can also fire multiple times per element (for example when text is split by entities or line breaks), so this example concatenates with .= style logic — here a single assignment is enough because each value is one short string.

xml_parser_create() is designed for event-driven parsing and does not perform schema validation. For XSD validation, the higher-level DOMDocument or SimpleXML extensions are recommended.

Conclusion

In this article, we've discussed PHP's xml_parser_create() function and how it can be used to create a new SAX-style XML parser. We've explained what the function does, its syntax, and provided examples of how to configure handlers and parse XML data sequentially. By following these examples, you can efficiently stream-parse XML files and extract specific data in your PHP applications. For most modern use cases, consider using SimpleXML or DOMDocument, which provide higher-level APIs and built-in validation without requiring manual parser setup.

Practice

Practice
What is the correct way to create an XML parser in PHP?
What is the correct way to create an XML parser in PHP?
Was this page helpful?