Welcome to The Coding College! In this tutorial, you will learn about the PHP XML Expat Parser, an event-based parser for processing XML documents. Unlike SimpleXML, the Expat parser processes XML data in real-time by triggering specific events as it parses through the XML file.
What is the XML Expat Parser?
The XML Expat Parser in PHP is based on the Expat library, which is an event-driven parser. It works by reading an XML document sequentially and triggering event handlers for different parts of the XML, such as opening/closing tags, text, or other components.
Key Features:
- Event-driven: You define functions (handlers) to process XML data when events occur.
- Lightweight and Fast: Parses data as it is read.
- Supports large XML files since it does not load the entire file into memory.
How the Expat Parser Works
To parse XML with Expat in PHP:
- Create a parser using
xml_parser_create(). - Assign handler functions for events (e.g., start tags, end tags, and character data).
- Parse the XML file or string using
xml_parse(). - Free the parser using
xml_parser_free().
Example XML File
Let’s use the following XML file for our examples:
books.xml:
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>Learning PHP</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book>
<title>Mastering MySQL</title>
<author>Jane Smith</author>
<price>34.99</price>
</book>
</library>Basic PHP Expat Parser Example
Here is a basic example demonstrating how to parse the above XML file:
Code:
<?php
// 1. Create an XML parser
$parser = xml_parser_create();
// 2. Define handler functions
function startElement($parser, $name, $attrs) {
echo "Start Tag: <$name><br>";
}
function endElement($parser, $name) {
echo "End Tag: </$name><br>";
}
function characterData($parser, $data) {
$data = trim($data);
if (!empty($data)) {
echo "Data: $data<br>";
}
}
// 3. Assign the handlers to the parser
xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");
// 4. Open and parse the XML file
$xmlFile = "books.xml";
if (!($handle = fopen($xmlFile, "r"))) {
die("Error: Could not open XML file.");
}
while ($data = fread($handle, 4096)) {
if (!xml_parse($parser, $data, feof($handle))) {
die(sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
}
// 5. Free the parser
xml_parser_free($parser);
fclose($handle);
?>Explanation
- Create Parser:
xml_parser_create()initializes the Expat parser. - Event Handlers:
xml_set_element_handler()assigns functions for start and end tags.xml_set_character_data_handler()handles the text between tags.
- Parse File: The XML file is read in chunks (4096 bytes) and passed to
xml_parse(). - Free Parser: Once done, the parser is released using
xml_parser_free().
Output:
Start Tag: <LIBRARY>
Start Tag: <BOOK>
Start Tag: <TITLE>
Data: Learning PHP
End Tag: </TITLE>
Start Tag: <AUTHOR>
Data: John Doe
End Tag: </AUTHOR>
Start Tag: <PRICE>
Data: 29.99
End Tag: </PRICE>
End Tag: </BOOK>
Start Tag: <BOOK>
Start Tag: <TITLE>
Data: Mastering MySQL
End Tag: </TITLE>
Start Tag: <AUTHOR>
Data: Jane Smith
End Tag: </AUTHOR>
Start Tag: <PRICE>
Data: 34.99
End Tag: </PRICE>
End Tag: </BOOK>
End Tag: </LIBRARY>Key XML Parser Functions
Here’s a breakdown of the key functions used in the Expat parser:
| Function | Purpose |
|---|---|
xml_parser_create() | Initializes the XML parser. |
xml_set_element_handler() | Sets handlers for start and end tags. |
xml_set_character_data_handler() | Sets the handler for character data (text). |
xml_parse() | Parses XML data incrementally. |
xml_parser_free() | Frees the parser resource after parsing is done. |
xml_get_error_code() | Retrieves the error code if parsing fails. |
xml_error_string() | Returns a string description of an XML error. |
xml_get_current_line_number() | Retrieves the line number where parsing failed. |
Advantages of Using Expat Parser
- Memory Efficiency: Since it processes the XML file sequentially, it can handle large files without consuming excessive memory.
- Speed: Event-driven parsing is faster because it does not load the full XML into memory.
- Flexibility: You can customize how different parts of the XML are processed.
Conclusion
The PHP XML Expat Parser is a powerful tool for processing XML data in a lightweight, event-driven way. By using event handlers, you can efficiently parse and interact with XML documents, even if they are very large.