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