PHP XML Expat Parser

Parse XML documents efficiently with PHP's built-in Expat parser

📄 What is XML Expat?

XML Expat is a fast, event-based XML parser built into PHP. It reads XML documents sequentially and triggers functions when it encounters elements, making it memory-efficient for large files.


<?php
// Simple XML string
$xml = "<note><to>John</to><from>Jane</from></note>";

// Create parser
$parser = xml_parser_create();
echo "Parser created successfully!";
?>
                                    

Output:

Parser created successfully!

Key Expat Concepts

The Expat parser uses event-driven functions to process XML. You define handler functions that execute when the parser encounters specific XML structures like opening tags, closing tags, or character data.

🔓

Start Element

Triggered when opening tag found

function start($parser, $name, $attrs) {
    echo "Start: $name";
}
🔒

End Element

Triggered when closing tag found

function end($parser, $name) {
    echo "End: $name";
}
📝

Character Data

Triggered for text content

function char($parser, $data) {
    echo "Data: $data";
}
⚙️

Parser Setup

Configure and execute parser

xml_set_element_handler(
    $parser, "start", "end"
);

🔹 Creating an Expat Parser

Follow these steps to create and configure an XML Expat parser:

<?php
// Step 1: Create parser
$parser = xml_parser_create();

// Step 2: Define handler functions
function startElement($parser, $name, $attrs) {
    echo "<b>Start tag: $name</b><br>";
}

function endElement($parser, $name) {
    echo "<b>End tag: $name</b><br>";
}

function characterData($parser, $data) {
    echo "Data: $data<br>";
}

// Step 3: Set handlers
xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");

// Step 4: Parse XML
$xml = "<note><to>John</to></note>";
xml_parse($parser, $xml);

// Step 5: Free parser
xml_parser_free($parser);
?>

Output:

Start tag: NOTE
Start tag: TO
Data: John
End tag: TO
End tag: NOTE

🔹 Parsing XML File

Read and parse XML from an external file:

<?php
// Create parser
$parser = xml_parser_create();

// Handler functions
function tagStart($parser, $name, $attrs) {
    echo "Opening: $name<br>";
}

function tagEnd($parser, $name) {
    echo "Closing: $name<br>";
}

// Set handlers
xml_set_element_handler($parser, "tagStart", "tagEnd");

// Open and parse file
$file = fopen("data.xml", "r");
while ($data = fread($file, 4096)) {
    xml_parse($parser, $data, feof($file));
}

// Clean up
fclose($file);
xml_parser_free($parser);
?>

Output:

Opening: CATALOG
Opening: BOOK
Closing: BOOK
Closing: CATALOG

🔹 Handling Attributes

Access XML element attributes in your handler functions:

<?php
$parser = xml_parser_create();

function startTag($parser, $name, $attrs) {
    echo "Element: $name<br>";
    if (!empty($attrs)) {
        foreach ($attrs as $key => $value) {
            echo "- Attribute: $key = $value<br>";
        }
    }
}

xml_set_element_handler($parser, "startTag", null);

$xml = '<book id="101" category="fiction"></book>';
xml_parse($parser, $xml);
xml_parser_free($parser);
?>

Output:

Element: BOOK
- Attribute: ID = 101
- Attribute: CATEGORY = fiction

🔹 Error Handling

Detect and handle XML parsing errors:

<?php
$parser = xml_parser_create();

// Invalid XML (missing closing tag)
$xml = "<note><to>John</to>";

if (!xml_parse($parser, $xml)) {
    echo "XML Error: " . xml_error_string(xml_get_error_code($parser)) . "<br>";
    echo "Line: " . xml_get_current_line_number($parser);
} else {
    echo "XML parsed successfully!";
}

xml_parser_free($parser);
?>

Output:

XML Error: Mismatched tag
Line: 1

🧠 Test Your Knowledge

What type of parser is XML Expat?