I have an xml file. Here's how it's formed:
<?xml version="1.0"?>
<export>
<config>
<exported_values>
<value1>Dog</value1>
<value2>Cat</value2>
<value3>Bird</value3>
<value4>Mouse</value4>
</exported_values>
<item name="orange" text="this is item 1" />
<item name="blue" text="this is item 2" />
<item name="yellow" text="this is item 3" />
<item name="green" text="this is item 4" />
</config>
</export>
How can i access the value of name inside item? I tried this without luck:
if( ! $xml = simplexml_load_file('xml/test.xml') ){
echo 'unable to load XML file';
} else {
foreach( $xml as $item )
{
echo 'item: '.$item->config->item['name'].'<br />';
}
}
But that does not return anything. Did i miss something?
Your problem is in the way you're trying to access the attributes from your XML nodes. Just update your foreach code to:
foreach( $xml->config->item as $item )
{
echo 'item: ', $item->attributes()->name, '<br />';
}
item: orange<br />item: blue<br />item: yellow<br />item: green<br />
You have $item->config->item
and $item
the wrong way around: the <config>
item only appears once, so accessing it every time round the loop would make no sense.
$xml
represents the <export>
node, and you want to loop over each of the several <item>
nodes in the single <config>
node, so the loop should be:
foreach( $xml->config->item as $item )
Then $item
will represent each particular <item>
node in the loop, so accessing the attribute will be as simple as:
echo $item['name'];
Here's a complete live example .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.