XML Parser - Code-Tips.com - Web Development, Programming, SEO

Saturday, May 9, 2009

XML Parser

The following php code processes an xml file and displays contents in the browser. Each element is displayed, followed by the name and value of any attributes. The text value will be disaplyed on if the element is not empty.

It uses various methods from the XMLReader class (php), to move through each element and attribute of the xml document displaying each element and attribute name, and any values.


Contents of sample.xml


<?xml version="1.0" ?>
<group name="Group 1">
<person>
<name>Sam</name>
</person>
<person>
<name>John</name>
<name something="asdjasd" />
</person>
</group>




Php code:


<?php

//Load the xml file
$styleDoc = new XMLReader();
$styleDoc->open("sample.xml");

//Find the first element
while ($styleDoc->name == "") {
$styleDoc->read();
}

//Save the name of the first/parent element
$parentNode = $styleDoc->name;

//Process each element/attribute in the xml file
do {

if ($styleDoc->name != "#text") {//Skip text in between elements
print $styleDoc->name;

if ($styleDoc->hasAttributes){
$numAttributes = $styleDoc->attributeCount;

//Loop through attributes
for ($i = 0; $i < $numAttributes; $i++) {       $styleDoc->moveToAttributeNo($i);
print "       " . $styleDoc->name . ": " . $styleDoc->value;
}
}
//Move to the element's vlaue
$styleDoc->read();

//Print the element's value
print "
-  " . $styleDoc->value . "
";
}
$styleDoc->read();

}while ($styleDoc->name != $parentNode);

//Print the closing parent node
print $styleDoc->name;
?>







Output:



group name: Group 1
-

person
-

name
- Sam
name
-

person
-

person
-

name
- John
name
-

name something: asdjasd
-

person
-

group

0 comments:

Post a Comment