Skip to content

PHP XML Expat

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.

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 parsing
libxml_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 errors
libxml_clear_errors();
?>

Explanation:

  1. libxml_use_internal_errors(true): Tells the underlying libxml library to suppress errors and store them internally, allowing us to fetch them later.
  2. simplexml_load_file(): Parses the XML file and returns a SimpleXMLElement object on success, or false on failure.
  3. Error Handling: We check if $xml is false. If so, we iterate through libxml_get_errors() to display parsing errors.
  4. Accessing Elements: Child elements are accessed like object properties (e.g., $xml->to, $xml->heading).
  5. Accessing Attributes: Attributes of the current element are accessed like array keys (e.g., $xml['importance']).
  6. Accessing Repeating Elements: When an element appears multiple times (like <tag>), accessing it (e.g., $xml->tags->tag) returns an iterable collection of SimpleXMLElement objects, which can be looped through using foreach.
  7. Security: Use htmlspecialchars() when outputting XML data to HTML to prevent Cross-Site Scripting (XSS) vulnerabilities.
  8. libxml_clear_errors(): Clears any stored libxml errors after processing.
  • 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.