← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 4 of 24

PHP XML Handling

What is XML?

XML represents structured data as nested tags, similar in spirit to HTML but designed for data exchange rather than display; PHP's SimpleXML extension turns an XML document into an easy-to-navigate object tree.

Example: What is XML?

php
<?php
$xml = simplexml_load_string("<book><title>PHP Basics</title></book>");
echo get_class($xml);
?>

Reading XML Elements

Once loaded with simplexml_load_string() or simplexml_load_file(), XML elements become accessible as regular object properties, so <book><title>...</title></book> becomes $book->title without manual parsing.

Example: Reading XML Elements

php
<?php
$xml = simplexml_load_string("<book><title>PHP Basics</title></book>");
echo $xml->title;
?>

Modifying XML Elements

Because SimpleXML elements behave like live references into the document, assigning a new value to $element->title actually updates the underlying XML structure, ready to be saved back out.

Example: Modifying XML Elements

php
<?php
$xml = simplexml_load_string("<book><title>Old Title</title></book>");
$xml->title = "New Title";
echo $xml->asXML();
?>

Creating XML with SimpleXML

addChild() and addAttribute() let you build XML documents programmatically from scratch, appending new nested elements and attributes onto an existing SimpleXMLElement.

Example: Creating XML with SimpleXML

php
<?php
$xml = new SimpleXMLElement("<book></book>");
$xml->addChild("title", "PHP Basics");
$xml->addAttribute("id", "1");
echo $xml->asXML();
?>

Looping Through XML Lists

When an XML document contains repeated elements (like multiple <item> tags), a standard foreach loop iterates over them cleanly, letting you process each one exactly like looping over an array.

Example: Looping Through XML Lists

php
<?php
$xml = simplexml_load_string("<items><item>A</item><item>B</item></items>");
foreach ($xml->item as $item) {
    echo $item . "\n";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.