PHP MySQL tutorial

XML DOM Parser

DOM stands for documented object model. Most of the scripting languages come with their own DOM. For instance html DOM consists of all the HTML tags, attributes and associated rules. Similarly, XML has its own DOM. PHP contains built in parser to read XML DOM. XML DOM parser is a tree based parser which treats XML nodes and elements as different levels within a tree. Consider the following XML document.


Mike
10
Male
City High School

Save the above code in the student.xml file.

XML DOM parser will see above XML document as tree having three levels. The first level is the XML document level. The root elements such as Name and Age are at level two and the level three is the text element level which is the value within the Name, Age or Gender tags.

In the following example PHP XML DOM parser is being used to retrieve and display values within all the tags in the student.xml document.

load("student.xml");

//Printing the contents of the document
print $xmlDom->saveXML();
?>

Download the code
Run the code

In the above code DomDocument object is being used to create XML DOM parser. The load method of the parser loads the file to parse and then he saveXML methods is used to retrieve the contents of the XML document.

Apart from displaying the contents of XML document, you can also loop through all the child nodes of a parent node via XML DOM parser. The following code loops through all the child elements of the Student node in the student.xml document. Have a look at it.


load("student.xml");

$nodes= $xmlDom->documentElement;

foreach ($nodes->childNodes AS $childitems) {
  print $childitems->nodeName . " => " . $childitems->nodeValue . "
"; } ?>

Download the code
Run the code

<<< Reading XML Nodes/Attributes Values in PHPSorting Arrays in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .