Parse XML in PHP Using SimpleXML
Parsing XML is a fundamental task in web development, and PHP’s SimpleXML extension provides an intuitive way to read and manipulate XML data. This article guides you through the process of loading XML from both files and strings, accessing elements and attributes, and iterating through repeating data nodes using clean, practical PHP examples.
Loading XML Data
SimpleXML provides two primary functions for loading XML, depending on whether your data source is a string or a external file.
Loading XML from a String
To parse XML data stored inside a PHP string variable, use the
simplexml_load_string() function.
<?php
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>12.99</price>
</book>
</bookstore>';
$xml = simplexml_load_string($xmlString);
if ($xml === false) {
die("Failed to load XML");
}
?>Loading XML from a File
To parse an external XML file (local or via a URL), use the
simplexml_load_file() function.
<?php
$xml = simplexml_load_file('books.xml');
if ($xml === false) {
die("Failed to load XML file");
}
?>Accessing XML Elements
SimpleXML converts XML elements into PHP objects, allowing you to
access child nodes using the standard object operator
(->).
// Accessing child elements directly
echo "Book Title: " . $xml->book->title . "\n";
echo "Author: " . $xml->book->author . "\n";Accessing XML Attributes
XML attributes are treated as array keys on the element object. You
can access them using square brackets ([]).
// Accessing the 'category' attribute of the book element
$category = $xml->book['category'];
echo "Category: " . $category . "\n";Iterating Through Multiple Elements
When dealing with multiple repeating elements, you can loop through
them using a standard foreach loop.
<?php
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>12.99</price>
</book>
<book category="classic">
<title>Moby Dick</title>
<author>Herman Melville</author>
<price>8.50</price>
</book>
</bookstore>';
$xml = simplexml_load_string($xmlString);
foreach ($xml->book as $book) {
echo "Title: " . $book->title . " (" . $book['category'] . ") - $" . $book->price . "\n";
}
?>Converting XML Node Values to PHP Types
By default, SimpleXML returns elements as
SimpleXMLElement objects. To use them as standard PHP
variables (such as strings or floats), cast them explicitly.
// Casting to string and float
$title = (string)$xml->book[0]->title;
$price = (float)$xml->book[0]->price;
var_dump($title); // string(16) "The Great Gatsby"
var_dump($price); // float(12.99)