PHP XML Handling
In this page:
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
$xml = simplexml_load_string("<book><title>PHP Basics</title></book>");
echo get_class($xml);
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = simplexml_load_string("<book><title>PHP Basics</title></book>");
echo $xml->title;
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = simplexml_load_string("<book><title>Old Title</title></book>");
$xml->title = "New Title";
echo $xml->asXML();
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = new SimpleXMLElement("<book></book>");
$xml->addChild("title", "PHP Basics");
$xml->addAttribute("id", "1");
echo $xml->asXML();
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = simplexml_load_string("<items><item>A</item><item>B</item></items>");
foreach ($xml->item as $item) {
echo $item . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser