Easy PHP SimpleXML Issue

谁都会走 提交于 2019-12-12 01:35:37

问题


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 array 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.


回答1:


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.




回答2:


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



回答3:


Is this it ? http://www.php.net/manual/fr/simplexmlelement.xpath.php




回答4:


Try foreach( $xml['data'] as $fruits=>$item )

---- edit ----

foreach( $xml as $fruits => $item ) {
    if( $fruits == "fruits" )
        $foodlist[] = $item;
}


来源:https://stackoverflow.com/questions/3917078/easy-php-simplexml-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!