PHP SimpleXML

Parse and manipulate XML documents easily

📄 What is SimpleXML?

SimpleXML is a PHP extension that converts XML documents into objects, making it easy to read, access, and manipulate XML data using simple object properties and methods.


<?php
$xml = simplexml_load_string('<book><title>PHP Guide</title></book>');
echo $xml->title; // Output: PHP Guide
?>
                                    

Key SimpleXML Functions

📂

Load File

Load XML from file

simplexml_load_file('data.xml');
📝

Load String

Parse XML from string

simplexml_load_string($xmlString);
🔍

XPath Query

Search XML with XPath

$xml->xpath('//book/title');

Add Child

Add new XML elements

$xml->addChild('name', 'value');

🔹 Loading XML from String

Parse XML data from a string using simplexml_load_string(). This converts the XML into an object that you can navigate using property syntax.

<?php
$xmlString = '<?xml version="1.0"?>
<library>
    <book>
        <title>PHP Basics</title>
        <author>John Doe</author>
        <price>29.99</price>
    </book>
</library>';

$xml = simplexml_load_string($xmlString);

echo "Title: " . $xml->book->title . "<br>";
echo "Author: " . $xml->book->author . "<br>";
echo "Price: $" . $xml->book->price;
?>

Output:

Title: PHP Basics
Author: John Doe
Price: $29.99

🔹 Loading XML from File

Read XML data directly from a file using simplexml_load_file(). This is useful when working with configuration files or data stored in XML format.

<?php
// Assuming books.xml exists with book data
$xml = simplexml_load_file('books.xml');

if ($xml === false) {
    echo "Failed to load XML file";
} else {
    echo "XML loaded successfully<br>";
    echo "Root element: " . $xml->getName();
}

// Example of what books.xml might contain:
/*
<?xml version="1.0"?>
<library>
    <book id="1">
        <title>Learning PHP</title>
    </book>
</library>
*/
?>

Output:

XML loaded successfully
Root element: library

🔹 Accessing XML Attributes

Read XML element attributes using array syntax. Attributes provide additional information about elements and are accessed differently than element content.

<?php
$xmlString = '<?xml version="1.0"?>
<library>
    <book id="101" category="programming">
        <title>PHP Advanced</title>
    </book>
</library>';

$xml = simplexml_load_string($xmlString);

// Access attributes
$book = $xml->book;
echo "Book ID: " . $book['id'] . "<br>";
echo "Category: " . $book['category'] . "<br>";
echo "Title: " . $book->title;
?>

Output:

Book ID: 101
Category: programming
Title: PHP Advanced

🔹 Looping Through Elements

Iterate through multiple XML elements using foreach loops. This is essential when processing XML documents with repeating elements like lists or collections.

<?php
$xmlString = '<?xml version="1.0"?>
<library>
    <book><title>PHP Basics</title><price>29.99</price></book>
    <book><title>MySQL Guide</title><price>34.99</price></book>
    <book><title>Web Development</title><price>39.99</price></book>
</library>';

$xml = simplexml_load_string($xmlString);

echo "Books in library:<br>";
foreach ($xml->book as $book) {
    echo "- " . $book->title . " ($" . $book->price . ")<br>";
}
?>

Output:

Books in library:
- PHP Basics ($29.99)
- MySQL Guide ($34.99)
- Web Development ($39.99)

🔹 Using XPath Queries

Search XML documents using XPath expressions to find specific elements based on complex criteria. XPath provides powerful querying capabilities for XML navigation.

<?php
$xmlString = '<?xml version="1.0"?>
<library>
    <book><title>PHP Basics</title><price>29.99</price></book>
    <book><title>MySQL Guide</title><price>34.99</price></book>
    <book><title>Web Dev</title><price>25.00</price></book>
</library>';

$xml = simplexml_load_string($xmlString);

// Find books with price less than 30
$cheapBooks = $xml->xpath('//book[price < 30]');

echo "Affordable books:<br>";
foreach ($cheapBooks as $book) {
    echo "- " . $book->title . "<br>";
}
?>

Output:

Affordable books:
- PHP Basics
- Web Dev

🔹 Adding New Elements

Create new XML elements dynamically using addChild(). This allows you to build or modify XML documents programmatically in your PHP applications.

<?php
$xmlString = '<?xml version="1.0"?><library></library>';
$xml = simplexml_load_string($xmlString);

// Add a new book
$book = $xml->addChild('book');
$book->addChild('title', 'New PHP Book');
$book->addChild('author', 'Jane Smith');
$book->addChild('price', '44.99');

// Display the updated XML
echo "Title: " . $xml->book->title . "<br>";
echo "Author: " . $xml->book->author . "<br>";
echo "Price: $" . $xml->book->price;
?>

Output:

Title: New PHP Book
Author: Jane Smith
Price: $44.99

🔹 Converting to Array

Convert SimpleXML objects to arrays for easier manipulation or integration with other PHP functions. This is useful when you need standard array operations.

<?php
$xmlString = '<?xml version="1.0"?>
<person>
    <name>John Doe</name>
    <age>30</age>
    <city>New York</city>
</person>';

$xml = simplexml_load_string($xmlString);

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

echo "Name: " . $array['name'] . "<br>";
echo "Age: " . $array['age'] . "<br>";
echo "City: " . $array['city'];
?>

Output:

Name: John Doe
Age: 30
City: New York

🧠 Test Your Knowledge

Which function loads XML from a file?