Easy PHP SimpleXML Issue
I've got a really bad brain block with this.
My XML file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<fruits>
<item>Apple</item>
<item>Orange</item>
<item>Banana</item>
</fruits>
<vegetables>
<item>Lettuce</item>
<item>Carrot</item>
</vegetables>
</data>
I am tyring to use SimpleXML to retrieve an a开发者_JAVA技巧rray containing "Apple, Orange, Banana". The code I am using is as follows:
$xml=simplexml_load_file('food.xml');
foreach($xml as $fruits=>$item) {
$foodlist[] = $item;
}
print_r($foodlist); // Should display list of fruits.
But the list of fruits is not being stored to the array. What am I doing wrong?
Much thanks.
How about this:
foreach($xml->fruits->item as $item) {
//$item has to be cast to a string otherwise it will be a SimpleXML element
$foodlist[] = (string) $item;
}
print_r($foodlist);
I think this should give you what you're looking for, an array containing the text value of each of the item nodes that are children of the fruits node.
I've tested your code. It works fine for me.
Another thing - it might be that you described it wrong, or might be that you understand this wrong. $foodlist should contain array of SimpleXML element objects (in your case "<fruits>
" and "<vegetables>
"), not array of fruits. If you want get only fruits you should access $xml->fruits->item;
.
Edit: if you want to build an array of fruits try this:
$array = (array)$xml->fruits;
print_r($array['item']); // Should dipslay list of fruits
//or this
foreach ($xml->fruits->item as $fruit){
$array2[] = (string) $fruit; //typecast to string, because $fruit is xml element object.
}
print_r($array2); // Should dipslay list of fruits
Is this it ? http://www.php.net/manual/fr/simplexmlelement.xpath.php
Try foreach( $xml['data'] as $fruits=>$item )
---- edit ----
foreach( $xml as $fruits => $item ) {
if( $fruits == "fruits" )
$foodlist[] = $item;
}
精彩评论