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

PHP SimpleXML Parser

XML data -- used for RSS feeds, configuration files, and many legacy APIs -- has a nested, tag-based structure quite different from JSON's simpler key-value shape. SimpleXML is PHP's easiest way to read XML: it converts an XML document directly into a PHP object whose properties mirror the XML's own tag structure.

Parsing an XML String

simplexml_load_string($xmlText) parses a string of XML text and returns a SimpleXMLElement object representing the document's structure -- each XML tag becomes an object property you can access with the normal -> operator, just like any other PHP object.

Note: Use simplexml_load_string() when your XML already exists as a string in memory, such as one returned by an API call.

Warning: Malformed XML (like a missing closing tag) causes simplexml_load_string() to return false and typically emit warnings, rather than throwing a catchable exception by default.

Example: Parsing an XML String

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

Loading XML from a File

simplexml_load_file($path) works exactly like simplexml_load_string(), but reads and parses the XML directly from a file path or a URL, saving you from manually reading the file's contents into a string first.

Note: Prefer simplexml_load_file() over combining file_get_contents() with simplexml_load_string() when reading XML from a file -- it is a single, simpler call.

Warning: simplexml_load_file() on a URL depends on PHP's allow_url_fopen setting being enabled, which some hosting environments disable for security reasons.

Example: Loading XML from a File

php
<?php
file_put_contents("data.xml", "<catalog><book>PHP Basics</book></catalog>");
$xml = simplexml_load_file("data.xml");
echo $xml->book;
?>

Accessing Nested Elements

Nested XML tags translate directly into nested object properties -- <catalog><book><title>...</title></book></catalog> becomes $catalog->book->title, letting you walk down through the XML's structure using the same -> chaining you would use for any nested PHP object.

Note: Read the XML's structure first (either by inspecting a sample file or its schema) before writing the PHP property chain to access a specific value.

Warning: Accessing a property that does not exist in the XML returns an empty SimpleXMLElement rather than null or triggering an error, which can make a missing-data bug harder to spot.

Example: Accessing Nested Elements

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

Looping Over Repeated Elements

When an XML document has multiple sibling elements with the same tag name (like several <item> entries inside a <catalog>), SimpleXML treats them as an iterable collection -- looping over $catalog->item with foreach visits each one in turn.

Note: Use foreach directly on the repeated element property, without needing to manually count or index into it.

Warning: When an XML tag appears only once, SimpleXML gives you a single object, not a one-item array -- foreach still works on it, but code that assumes it is always a countable array can behave unexpectedly if the count changes to exactly one.

Example: Looping Over Repeated Elements

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

Converting SimpleXML to an Array

While SimpleXMLElement objects work well for direct property access, converting one to a plain PHP array with json_decode(json_encode($xml), true) is a handy trick when you want to work with the data using ordinary array functions instead of object syntax.

Note: Reach for the json_encode/json_decode conversion trick specifically when you need array-style operations (like array_map or array_filter) on XML-derived data.

Warning: The json_encode/json_decode conversion trick can lose some XML-specific details, like attributes or a distinction between an empty tag and one containing an empty string.

Example: Converting SimpleXML to an Array

php
<?php
$xml = simplexml_load_string("<catalog><book>PHP Basics</book></catalog>");
$array = json_decode(json_encode($xml), true);
print_r($array);
?>
Common Mistakes
  1. Assuming SimpleXML objects behave exactly like plain arrays or objects for every operation -- some things (like isset checks on repeated elements) work a bit differently than expected.
  2. Forgetting to check that simplexml_load_file() or simplexml_load_string() actually succeeded before trying to read properties from a false result.
  3. Not casting a SimpleXMLElement value to a string or appropriate type before using it in string comparisons or concatenation, since it is technically its own object type.
Chapter Summary
  • simplexml_load_string($xmlText) parses an XML string into a SimpleXMLElement object.
  • simplexml_load_file($path) does the same, loading directly from a file path or URL.
  • Nested XML tags become nested object properties, accessed with the normal -> operator.
Browser Support

SimpleXML has been a core PHP extension since PHP 5 and is enabled by default in most standard PHP installations.

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.