PHP XML Parser
PHP is a popular scripting language used for web development. It allows developers to create dynamic websites and web applications by embedding PHP code within
PHP is a popular scripting language for web development, allowing developers to create dynamic websites by embedding code within HTML. One of its most useful features is its ability to work with XML, a markup language designed for storing and transporting data.
In this guide, we'll cover PHP's XML functionality, including its advantages, syntax, and usage examples. By the end, you'll understand how to work with XML to build better websites and applications.
What is XML?
XML stands for "eXtensible Markup Language." It is a markup language that allows developers to define their own tags and document structures, making it a highly flexible and customizable language. XML is commonly used for storing and transporting data, such as in web services, databases, and RSS feeds.
XML is similar to HTML, but whereas HTML defines how web pages are displayed in a browser, XML defines the structure and content of data. XML tags are used to identify data elements and their relationships, making it easy to transfer data between different systems.
Advantages of Using XML in PHP
Using XML in PHP offers several advantages, including:
- Data exchange: XML is an ideal format for exchanging data between different systems and platforms. Because XML is platform-independent, data can be easily transferred between systems regardless of the operating system or programming language used.
- Data storage: XML is a great way to store and organize data in a structured format. By using XML to store data, developers can easily access and manipulate the data as needed.
- Data transformation: XML can be easily transformed into other formats, such as HTML, PDF, and CSV, using XSLT (Extensible Stylesheet Language Transformations).
Syntax of XML in PHP
To work with XML in PHP, you'll need to be familiar with the syntax used to define XML documents. XML documents consist of elements, attributes, and values.
Elements are defined using opening and closing tags, such as <book> and </book>. Elements can also contain child elements, such as:
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>Attributes are used to provide additional information about elements, such as:
<book id="1234">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>Values are the content of an element, such as "The Great Gatsby" or "F. Scott Fitzgerald."
Which XML approach should you use?
PHP ships three parsers, and choosing the right one matters:
- SimpleXML — the easiest API. It turns an XML document into an object tree you navigate with normal property syntax (
$xml->book->title). Best for small-to-medium documents with a known structure. This guide focuses on SimpleXML; see PHP SimpleXML for a deeper reference. - DOMDocument (the DOM extension) — a full W3C DOM implementation. More verbose, but it lets you create, move, and remove nodes precisely, and it's required for XSLT and validation. See PHP XML DOM.
- XMLReader / XMLWriter — a streaming, pull-based parser. It reads one node at a time instead of loading the whole tree into memory, so it's the right choice for very large files (hundreds of MB) where SimpleXML and DOM would exhaust memory.
The historical xml_parser_create() SAX functions still exist but are rarely used in new code; SimpleXML covers the same ground with far less boilerplate.
Reading an XML document with SimpleXML
To load an XML file into an object tree, use the simplexml_load_file() function. If the source is a string (for example, an API response) rather than a file, use simplexml_load_string() instead.
Always check the return value: on a malformed document both functions return false rather than throwing, so an unchecked result is a common source of silent bugs.
$xml = simplexml_load_file("books.xml");
if ($xml === false) {
echo "Failed to load XML file.";
exit;
}This reads the XML file and converts it into a SimpleXMLElement object, which you access using PHP's object-oriented syntax. Child elements become properties, and repeated elements (like multiple <book> tags) behave like an iterable list.
Reading attributes
Attributes are not properties — you read them with array syntax on the element. Given <book id="1234">, the id is $book['id']:
$xml = simplexml_load_string('<book id="1234"><title>The Great Gatsby</title></book>');
echo $xml['id']; // 1234
echo $xml->title; // The Great GatsbyNote that SimpleXML values are objects, not plain strings. Cast with (string) when you need a real string (for instance, before a strict comparison or json_encode).
Writing an XML document with SimpleXML
To build XML from scratch, create a SimpleXMLElement with a root element and add children with addChild():
$xml = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book');
$book->addChild('title', 'The Great Gatsby');
$book->addChild('author', 'F. Scott Fitzgerald');
$xml->asXML('books.xml');This creates a SimpleXMLElement with the root element <books>, adds a <book> child with <title> and <author> children, and saves the document to books.xml. Calling asXML() with no argument returns the XML as a string instead of writing a file, which is handy when you need to send it in an HTTP response.
Usage Examples
Let's take a look at some practical examples of using XML in PHP.
Reading XML Data
Suppose you have an XML file called "books.xml" with the following data:
<books>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
</book>
</books>To read this data in PHP, you can use the simplexml_load_file() function, like this:
$xml = simplexml_load_file("books.xml");
if ($xml === false) {
echo "Failed to load XML file.";
exit;
}
foreach ($xml->book as $book) {
echo $book->title . " by " . $book->author . "\n";
}This code loads the XML file into a SimpleXMLElement object, and then iterates over each <book> element using a foreach loop. Within the loop, it accesses the <title> and <author> child elements using object-oriented syntax, and prints them out to the console.
Writing XML Data
Suppose you want to create a new XML file with the following data:
<colors>
<color>
<name>Red</name>
<hex>#FF0000</hex>
</color>
<color>
<name>Green</name>
<hex>#00FF00</hex>
</color>
<color>
<name>Blue</name>
<hex>#0000FF</hex>
</color>
</colors>To create this XML data in PHP, you can use the SimpleXMLElement class, like this:
$xml = new SimpleXMLElement('<colors></colors>');
$red = $xml->addChild('color');
$red->addChild('name', 'Red');
$red->addChild('hex', '#FF0000');
$green = $xml->addChild('color');
$green->addChild('name', 'Green');
$green->addChild('hex', '#00FF00');
$blue = $xml->addChild('color');
$blue->addChild('name', 'Blue');
$blue->addChild('hex', '#0000FF');
$xml->asXML('colors.xml');This code creates a new SimpleXMLElement object with the root element <colors>. It then adds three child elements <color>, each with two child elements <name> and <hex>, and sets their values accordingly. Finally, it saves the XML document to a file called "colors.xml."
Common gotchas
- Unchecked load result.
simplexml_load_file()andsimplexml_load_string()returnfalse, notnull, on a parse error. Test with=== falsebefore using the result. - Values are objects, not strings.
$xml->titleis aSimpleXMLElement. It works in string contexts (echo, concatenation) but fails surprising comparisons; cast with(string)when in doubt. - Suppressed parse errors. To inspect why parsing failed, call
libxml_use_internal_errors(true)before loading, then readlibxml_get_errors(). - Namespaces. If your XML uses namespaces (e.g.
xmlns:), plain property access won't find the elements — usechildren()orxpath()with the namespace registered. - Untrusted input. Don't parse XML from untrusted sources without care: external entity (XXE) attacks are a real risk. On modern PHP the relevant entity loading is disabled by default, but verify before processing user-supplied XML.
Related topics
- PHP SimpleXML — full reference for the SimpleXML extension.
- simplexml_load_file() and simplexml_load_string() — the two loader functions in detail.
- PHP XML DOM — the more powerful DOMDocument API.
- PHP JSON — the lighter-weight alternative for data interchange.
Conclusion
In this guide we covered what XML is, why it's useful, and how to read, write, and manipulate XML in PHP with the SimpleXML library, plus the common pitfalls to watch for. SimpleXML is the quickest way to handle structured XML data in PHP; reach for DOMDocument when you need fine-grained node control and XMLReader for very large files. Note that PHP's XML functions require the libxml extension, which is enabled by default in most standard installations.