PHP SimpleXML Examples

Learn how to read and manipulate XML data effortlessly using PHP's SimpleXML parser with practical examples.

📝 1. Read XML Data From a String

The simplexml_load_string() function is used to convert well-formed XML string data into a SimpleXMLElement object.

<?php
$myXMLData =
"<?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 = simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
?>

📂 2. Read XML Data From a File

Use the simplexml_load_file() function to load and parse an external XML document into an object.

<?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>

🔍 3. Get Specific Node Values

Once loaded into an object, you can access the XML nodes easily by treating them as object properties.

<?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");

echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

📚 4. Access Node Values of Specific Elements (Arrays)

If there are multiple elements with the same node name, SimpleXML treats them as an array. You can access specific elements using an index.

<?php
$xml = simplexml_load_file("books.xml") or die("Error: Cannot create object");

echo $xml->book[0]->title . "<br>";
echo $xml->book[1]->title;
?>

🔄 5. Loop Through Node Values

Use the `children()` method inside a foreach loop to gracefully iterate through all XML children nodes.

<?php
$xml = simplexml_load_file("books.xml") or die("Error: Cannot create object");

foreach($xml->children() as $books) {
    echo $books->title . ", ";
    echo $books->author . ", ";
    echo $books->year . ", ";
    echo $books->price . "<br>";
}
?>

🏷️ 6. Get Attribute Values

Attributes can be accessed directly using standard array syntax `['attribute_name']` on the element.

<?php
$xml = simplexml_load_file("books.xml") or die("Error: Cannot create object");

echo $xml->book[0]['category'] . "<br>";
echo $xml->book[1]->title['lang'];
?>

🔁 7. Loop Through Attribute Values

Similarly, you can loop through children nodes and access their respective attributes efficiently.

<?php
$xml = simplexml_load_file("books.xml") or die("Error: Cannot create object");

foreach($xml->children() as $books) {
    echo $books->title['lang'];
    echo "<br>";
}
?>