Reputation: 893
I want to loop through an xml file using simplephp.
My code for accessing is something like this:
// get the path of the file
$file = "xml/".$item_name . "_cfg.xml";
if( ! $xml = simplexml_load_file($file) ){
echo 'unable to load XML file';
} else {
$item_array = array();
foreach($xml->config->exported->item as $items)
{
$item_name = (string) $items->attributes()->name;
echo "item name: " . $item_name . "<br />";
}
That will echo out the name of all the item names in this xml, this isnt the actual xml as some of the data is sensitive but its basically the same with different data.
So it will show as the following based on the xml below:
yellow
blue
orange
red
black
here is the xml
<?xml version="1.0"?>
<main>
<config>
<exported>
<items>
<item name="yellow"></item>
<item name="blue"></item>
<New_Line />
<item name="orange"></item>
<item name="red"></item>
<New_Line />
<item name="black"></item>
</items>
</exported>
</config>
<main>
That is good but what i need to display is:
yellow
blue
--------
orange
red
--------
black
If you notice in the xml there is this line in between some of the stats
<New_Line />
And when i encounter that i want to echo a few dashes but i am not really sure how you do it as I'm not familiar with simplexml
Upvotes: 0
Views: 558
Reputation: 97688
Arguably this is a poor choice of structure in the XML, since what is presumably actually meant is that there are multiple sets of item
s, which should therefore have some parent to represent each individual group. Nonetheless, what you want to do is pretty easy using SimpleXML.
The trick is to use the ->children()
method to iterate over all child nodes in order, regardless of their name. Then within that loop, you can examine the name of each node using ->getName()
and decide how to act.
Here's an example (and a live demo of it in action); note that I've added the ->items
to match the sample XML you gave, and used the shorter $node['name']
rather than $node->attributes()->name
.
foreach($xml->config->exported->items->children() as $node)
{
switch ( $node->getName() )
{
case 'item':
$item_name = (string)$node['name'];
echo "item name: " . $item_name . "<br />";
break;
case 'New_Line':
echo '<hr />';
break;
}
}
Upvotes: 1