PHP SimpleXML Parser

Easy and intuitive XML parsing in PHP

✨ What is SimpleXML?

SimpleXML is PHP's easiest way to parse XML documents. It converts XML into an object structure, allowing you to access elements using simple object properties and array notation.


<?php
$xml = simplexml_load_string($xmlData);
echo $xml->title; // Access element directly
?>
                                    

SimpleXML Features

🎯

Simple Syntax

Easy object-oriented access

$xml->book->title
📂

Load Methods

Load from string or file

simplexml_load_file()
🔍

XPath Support

Query XML with XPath

$xml->xpath('//book')
🏷️

Attributes

Easy attribute access

$xml->book['id']

🔹 Loading XML Data

SimpleXML provides two main functions to load XML: simplexml_load_string() for XML strings and simplexml_load_file() for XML files:

<?php
// Method 1: Load from string
$xmlString = '<?xml version="1.0"?>
<bookstore>
    <book>
        <title>PHP Basics</title>
        <author>John Doe</author>
        <price>29.99</price>
    </book>
</bookstore>';

$xml = simplexml_load_string($xmlString);
echo "Title: " . $xml->book->title . "<br>";
echo "Author: " . $xml->book->author . "<br>";
echo "Price: $" . $xml->book->price;

// Method 2: Load from file
// $xml = simplexml_load_file("books.xml");
?>

Output:

Title: PHP Basics

Author: John Doe

Price: $29.99

🔹 Accessing XML Elements

Access XML elements using object notation. For multiple elements with the same name, use array-style access or foreach loops:

<?php
$xmlString = '<?xml version="1.0"?>
<library>
    <book>
        <title>Learning PHP</title>
        <author>Alice Smith</author>
    </book>
    <book>
        <title>Advanced PHP</title>
        <author>Bob Johnson</author>
    </book>
    <book>
        <title>PHP Mastery</title>
        <author>Carol White</author>
    </book>
</library>';

$xml = simplexml_load_string($xmlString);

// Loop through all books
foreach ($xml->book as $book) {
    echo "Title: " . $book->title . "<br>";
    echo "Author: " . $book->author . "<br><br>";
}
?>

Output:

Title: Learning PHP

Author: Alice Smith


Title: Advanced PHP

Author: Bob Johnson


Title: PHP Mastery

Author: Carol White

🔹 Working with Attributes

XML attributes can be accessed using array notation with the attribute name as the key:

<?php
$xmlString = '<?xml version="1.0"?>
<catalog>
    <product id="101" category="electronics">
        <name>Laptop</name>
        <price currency="USD">999.99</price>
    </product>
    <product id="102" category="books">
        <name>PHP Guide</name>
        <price currency="USD">39.99</price>
    </product>
</catalog>';

$xml = simplexml_load_string($xmlString);

foreach ($xml->product as $product) {
    // Access attributes
    echo "Product ID: " . $product['id'] . "<br>";
    echo "Category: " . $product['category'] . "<br>";
    echo "Name: " . $product->name . "<br>";
    echo "Price: " . $product->price . " " . $product->price['currency'] . "<br><br>";
}
?>

Output:

Product ID: 101

Category: electronics

Name: Laptop

Price: 999.99 USD


Product ID: 102

Category: books

Name: PHP Guide

Price: 39.99 USD

🔹 Using XPath Queries

XPath allows you to search for specific elements in XML documents using path expressions:

<?php
$xmlString = '<?xml version="1.0"?>
<store>
    <book category="fiction">
        <title>The Great Novel</title>
        <price>15.99</price>
    </book>
    <book category="programming">
        <title>PHP Programming</title>
        <price>45.99</price>
    </book>
    <book category="programming">
        <title>Web Development</title>
        <price>39.99</price>
    </book>
</store>';

$xml = simplexml_load_string($xmlString);

// Find all programming books
$programmingBooks = $xml->xpath('//book[@category="programming"]');

echo "Programming Books:<br>";
foreach ($programmingBooks as $book) {
    echo "- " . $book->title . " ($" . $book->price . ")<br>";
}

// Find books cheaper than $40
echo "<br>Books under $40:<br>";
$cheapBooks = $xml->xpath('//book[price < 40]');
foreach ($cheapBooks as $book) {
    echo "- " . $book->title . "<br>";
}
?>

Output:

Programming Books:

- PHP Programming ($45.99)

- Web Development ($39.99)


Books under $40:

- The Great Novel

- Web Development

🔹 Converting to Array

You can convert SimpleXML objects to arrays for easier manipulation or JSON encoding:

<?php
$xmlString = '<?xml version="1.0"?>
<user>
    <name>John Doe</name>
    <email>[email protected]</email>
    <age>30</age>
</user>';

$xml = simplexml_load_string($xmlString);

// Convert to array
$array = json_decode(json_encode($xml), true);

// Display as array
echo "User Data:<br>";
echo "Name: " . $array['name'] . "<br>";
echo "Email: " . $array['email'] . "<br>";
echo "Age: " . $array['age'] . "<br><br>";

// Convert to JSON
$json = json_encode($xml);
echo "JSON: " . $json;
?>

Output:

User Data:

Name: John Doe

Email: [email protected]

Age: 30


JSON: {"name":"John Doe","email":"[email protected]","age":"30"}

🔹 Error Handling

Always handle errors when loading XML to prevent script failures:

<?php
$xmlString = '<?xml version="1.0"?>
<data>
    <item>Valid XML</item>
</data>';

// Disable error output
libxml_use_internal_errors(true);

$xml = simplexml_load_string($xmlString);

if ($xml === false) {
    echo "Failed to load XML:<br>";
    foreach(libxml_get_errors() as $error) {
        echo "- " . $error->message . "<br>";
    }
    libxml_clear_errors();
} else {
    echo "XML loaded successfully!<br>";
    echo "Content: " . $xml->item;
}
?>

Output:

XML loaded successfully!

Content: Valid XML

🔹 SimpleXML Tips

💡 Best Practices:

  • File size: Best for XML files under 10MB
  • Error handling: Always use libxml_use_internal_errors()
  • Type casting: Cast to string when needed: (string)$xml->element
  • Namespaces: Use children() method for namespaced elements
  • Memory: Loads entire document into memory

🧠 Test Your Knowledge

How do you access an XML attribute in SimpleXML?