1 min read

PHP XML Handling (SimpleXML)

XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. PHP's SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.


1. Loading XML

You can load XML from a string or a file.

From String

$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);

From File

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

2. Accessing Elements

You can access element values by using the element name as a property of the object.

echo $xml->to;
echo $xml->from;

3. Looping Through Elements

If an element contains multiple children with the same name, you can loop through them.

foreach($xml->children() as $child) {
    echo $child->getName() . ": " . $child . "<br>";
}

4. Getting Attribute Values

Attributes are accessed using array notation.

/* <book category="COOKING"> */
echo $xml->book[0]['category'];

programming/php/php