简单的 PHP SimpleXML 问题
我对此有严重的脑梗塞。
我的 XML 文件如下所示:
<?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>
我试图使用 SimpleXML 来检索包含“Apple、Orange、Banana”的数组。我使用的代码如下:
$xml=simplexml_load_file('food.xml');
foreach($xml as $fruits=>$item) {
$foodlist[] = $item;
}
print_r($foodlist); // Should display list of fruits.
但是水果列表没有存储到数组中。我做错了什么?
非常感谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
我认为这应该为您提供您正在寻找的内容,一个数组,其中包含作为水果节点子节点的每个项目节点的文本值。
How about this:
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.
我已经测试了你的代码。它对我来说效果很好。
还有一件事——可能是你描述错误,或者可能是你理解错误。 $foodlist 应包含 SimpleXML 元素对象数组(在您的情况下为“
”和“
”),而不是水果数组。如果您只想获取水果,您应该访问$xml->fruits->item;
。编辑:
如果你想构建一系列水果,请尝试以下操作:
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:
是这个吗? http://www.php.net/manual/fr/simplexmlelement.xpath.php
Is this it ? http://www.php.net/manual/fr/simplexmlelement.xpath.php
尝试
foreach( $xml['data'] as $fruits=>$item )
---- 编辑 ----
Try
foreach( $xml['data'] as $fruits=>$item )
---- edit ----