Skip to content

PHP SimpleXML Parser

SimpleXML is a PHP extension that provides an intuitive and easy-to-use interface for parsing and manipulating XML data.

SimpleXML works best with uncomplicated, record-like XML structures. It represents an XML document as an object, allowing you to access elements and attributes using standard object property and array index notation.

Key features:

  • Tree-Based: Parses the entire XML document into a tree structure in memory.
  • Easy Access: Provides simple syntax (like $xml->element or $xml['attribute']) to navigate and retrieve data, assuming you know the XML structure.
  • Iteration: Allows easy iteration over elements with the same name using loops (like foreach).
  • Conciseness: Often requires less code to read simple XML data compared to DOM or Expat parsers.

The SimpleXML extension is part of the PHP core and is enabled by default in modern PHP installations. No separate installation is required.

The simplexml_load_string() function parses XML data stored in a PHP string variable.

Consider this XML data stored in a string:

<?php
$myXMLData = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;
?>

Here’s how to parse it using simplexml_load_string():

<?php
$myXMLData = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;
// Crucial for security when dealing with potentially untrusted XML
// to prevent XXE attacks. Disable before loading.
libxml_disable_entity_loader(true);
$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML string.<br>";
// Optional: Display specific errors (see error handling example below)
foreach(libxml_get_errors() as $error) {
echo htmlspecialchars($error->message), "<br>";
}
exit;
}
// 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>";
// For debugging: view the structure
// echo "<pre>";
// print_r($xml);
// echo "</pre>";
?>

Output of the above code:

To: Tove<br>
From: Jani<br>
Heading: Reminder<br>
Body: Don't forget me this weekend!<br>

SimpleXML relies on the underlying libxml library. To properly handle XML parsing errors, use the libxml error handling functions:

<?php
// Enable user error handling for libxml
libxml_use_internal_errors(true);
// Disable external entity loading for security
libxml_disable_entity_loader(true);
$brokenXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john@example.com</wrongemail>
</document>";
$xml = simplexml_load_string($brokenXMLData);
if ($xml === false) {
echo "**Failed loading XML:**<br>";
$errors = libxml_get_errors();
foreach ($errors as $error) {
// Display error details (level, code, message, file, line, column)
echo " - Level ". htmlspecialchars($error->level) .": " . htmlspecialchars(trim($error->message)) . " on line " . htmlspecialchars($error->line) ."<br>";
}
// Clear the error buffer after handling
libxml_clear_errors();
} else {
echo "XML loaded successfully (though it might have non-fatal issues if not fully checked).";
// Process the $xml object here...
// print_r($xml);
}
// Optionally restore default error handling if needed later in the script
// libxml_use_internal_errors(false);
?>

Output for the broken XML:

**Failed loading XML:**<br>
- Level 3: Opening and ending tag mismatch: user line 3 and wronguser on line 3<br>
- Level 3: Opening and ending tag mismatch: email line 4 and wrongemail on line 4<br>

Security Note: Always use libxml_disable_entity_loader(true); before loading XML from untrusted sources (including external files or user input) to prevent XML External Entity (XXE) vulnerabilities.

The simplexml_load_file() function parses XML data directly from a file path or URL.

Assume we have an XML file named note.xml with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example below shows how to parse this file:

<?php
// Enable user error handling and disable entity loader
libxml_use_internal_errors(true);
libxml_disable_entity_loader(true);
$xmlFile = 'note.xml';
if (!file_exists($xmlFile)) {
die("Error: File not found ($xmlFile)");
}
$xml = simplexml_load_file($xmlFile);
if ($xml === false) {
echo "Failed loading XML file: $xmlFile<br>";
foreach(libxml_get_errors() as $error) {
echo htmlspecialchars(trim($error->message)), "<br>";
}
libxml_clear_errors();
exit;
}
// Access data as before
echo "To: " . htmlspecialchars($xml->to) . "<br>";
echo "From: " . htmlspecialchars($xml->from) . "<br>";
// ... and so on
// Example of accessing an attribute if one existed (e.g., <note id="123">)
// echo "Note ID: " . htmlspecialchars($xml['id']) . "<br>";
?>

The output (assuming note.xml exists and is valid) would be similar to the string example.

Tip: Subsequent chapters will delve deeper into accessing specific node values, attributes, and handling more complex XML structures with SimpleXML.

For a complete list of SimpleXML functions and more detailed examples, refer to the official PHP documentation or dedicated SimpleXML tutorials.