
As we all know XML documents are used to store and describe the structure of data. It is often used to transport data over internet, for instance if you use any Google API then it's response is in either XML or JSON. We need to extract required data from XML file and it can be done with the help of XML parsers. There are various parser available like DOM parser and SimpleXML parser. Below I have shown how to make use of it to parse any XML documents.
Parsing XML using DOM Parser
DOM parser is a tree based parser that means it sees any XML document as a tree structure. Below is the tree structure of an XML document.

Suppose we need to parse below xml.
1: xml version="1.0" encoding="ISO-8859-1"?>
2: <article>
3: <title>How To Parse XML in PHP</title>
4: <author>Sumit Jha</author>
5: <site>www.sumitjha.net</site>
6: </article>
Load and Output XML
To display the content/data of XML we need to first initialize the DOM parser then load the XML document.
1: php
2: $xmlDoc = new DOMDocument();
3: $xmlDoc->load("article.xml");4: print $xmlDoc->saveXML();
5: ?>
The output of above code will be
How To Parse XML in PHP Sumit Jha www.sumitjha.net
Explanation:
DOMDocument() : It creates a DOMDocument-Object to load XML in tree structure form.
load() : Load the XML file
saveXML() : It puts the internal XML file into a string.
Looping through XML
We can also loop though root node an traverse all of its child according to it’s structure.
php
$xmlDoc = new DOMDocument();
$xmlDoc->load("article.xml");$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{print $item->nodeName . " = " . $item->nodeValue . "
";
}
?>
output:
#text =
title = How To Parse XML in PHP
#text =
author = Sumit Jha
#text =
site = www.sumitjha.net
#text =
Explanation:
Starting from root node we traverse all the child node and output their value.
Note the empty text node between each element. This is because when XML generated it contain white spaces between the nodes and DOM parser treat it as an element.
Parsing XML using SimpleXML Parser
As the name suggest SimpleXML parser is an easy to use parser to fetch an element's attributes and text, all you need to know is the layout of XML document.
php
$xml = simplexml_load_file("article.xml");echo $xml->getName() . "
";
foreach($xml->children() as $child)
{echo $child->getName() . ": " . $child->name . "
";
}
?>
Output:
article
title: How To Parse XML in PHP
author: Sumit Jha
site: www.sumitjha.net
Explanation:
We first load the XML file and get the name of first element i.e, the root node. Here in this case the root node is article. Now we loop though the each child node of article.
Note: We also fetch any node directly from XML document using it’s exact path from root.
$xml->site will return
www.sumitjha.net