XML (Extensible Markup Language) is a data format used to store and transport data. While JSON has become more popular in recent years, XML is still widely used in many legacy systems, RSS feeds, and enterprise web services. PHP provides several ways to parse XML, with **SimpleXML** being the most user-friendly.
SimpleXML is a PHP extension that allows you to easily convert XML data into an object that you can navigate like any other PHP object.
If you have XML data stored in a variable, you can use simplexml_load_string().
<?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);
echo $xml->to; // Outputs: Tove
echo $xml->heading; // Outputs: Reminder
?>
If your XML data is in a file (e.g., note.xml), use simplexml_load_file().
<?php
$xml = simplexml_load_file("note.xml");
echo $xml->to;
?>
If your XML has multiple elements (like a list of books), you can use a foreach loop to iterate through them.
<?php
$xml = simplexml_load_file("books.xml");
foreach($xml->children() as $book) {
echo $book->title . " by " . $book->author . "<br>";
}
?>
To access attributes of an XML tag, you use array syntax on the object property.
<?php
// XML: <book id='1'>...</book>
echo $xml->book[0]['id']; // Outputs the 'id' attribute of the first book
?>
false and generate warnings. Always check your XML source!
Handling data often involves making sure it is safe and valid. Let's explore how to protect your application in the **PHP Filters & Validation** lesson.