PHP XML Expat
PHP XML Processing with SimpleXML
Section titled “PHP XML Processing with SimpleXML”The SimpleXML extension provides a very straightforward way to parse and browse XML documents in PHP. It represents the XML document as an object, making data access feel natural.
SimpleXML is generally the easiest method for reading data from simple, well-structured XML files or strings.
Parsing an XML Document
Section titled “Parsing an XML Document”You can load XML from a file or directly from a string.
The Example XML File (note.xml):
<?xml version="1.0" encoding="UTF-8"?><note importance="high"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> <tags> <tag>urgent</tag> <tag>personal</tag> </tags></note>Loading and Parsing with PHP:
<?php// Ensure errors are reported for XML parsinglibxml_use_internal_errors(true);
$xmlFile = 'note.xml';
if (file_exists($xmlFile)) { $xml = simplexml_load_file($xmlFile);
if ($xml === false) { echo "Failed loading XML\n"; foreach(libxml_get_errors() as $error) { echo "\t", $error->message; } } else { // Accessing elements as object properties echo "To: " . htmlspecialchars($xml->to) . "<br>"; echo "From: " . htmlspecialchars($xml->from) . "<br>"; echo "Heading: " . htmlspecialchars($xml->heading) . "<br>"; echo "Body: " . htmlspecialchars($xml->body) . "<br>";
// Accessing attributes as array keys echo "Importance: " . htmlspecialchars($xml['importance']) . "<br>";
// Accessing repeating elements (like <tag>) echo "Tags: "; foreach ($xml->tags->tag as $tag) { echo htmlspecialchars($tag) . " "; } echo "<br>"; }} else { echo "File not found: $xmlFile";}
// Clear libxml errorslibxml_clear_errors();
?>Explanation:
libxml_use_internal_errors(true): Tells the underlying libxml library to suppress errors and store them internally, allowing us to fetch them later.simplexml_load_file(): Parses the XML file and returns aSimpleXMLElementobject on success, orfalseon failure.- Error Handling: We check if
$xmlisfalse. If so, we iterate throughlibxml_get_errors()to display parsing errors. - Accessing Elements: Child elements are accessed like object properties (e.g.,
$xml->to,$xml->heading). - Accessing Attributes: Attributes of the current element are accessed like array keys (e.g.,
$xml['importance']). - Accessing Repeating Elements: When an element appears multiple times (like
<tag>), accessing it (e.g.,$xml->tags->tag) returns an iterable collection ofSimpleXMLElementobjects, which can be looped through usingforeach. - Security: Use
htmlspecialchars()when outputting XML data to HTML to prevent Cross-Site Scripting (XSS) vulnerabilities. libxml_clear_errors(): Clears any stored libxml errors after processing.
When to Use Other Parsers
Section titled “When to Use Other Parsers”- DOMDocument: Use when you need more control, like modifying the XML structure extensively, validating against a DTD/Schema, or dealing with namespaces in complex ways.
- XMLReader: Use for extremely large XML files where loading the entire document into memory (like SimpleXML and DOM do) is not feasible. It reads the file sequentially.
- XML Parser (Expat): A low-level, event-based parser. Also suitable for very large files or specific stream-processing tasks, but generally more complex to implement due to its callback-based nature.
For many typical web development tasks involving reading configuration or data from moderately sized XML files, SimpleXML offers a good balance of ease-of-use and capability.
For more detailed information on SimpleXML functions and methods, refer to the official PHP documentation.