使用SimpleXML从XML获取多个项目 [英] Get multiple items from XML with SimpleXML
本文介绍了使用SimpleXML从XML获取多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用下面的代码从XML中循环多个项目.
I'm trying to loop multiple items from an XML with the code below.
$xml = get_data('the-url');
$data = simplexml_load_string($xml);
foreach($data->item AS $item) {
foreach($item AS $test) {
var_dump($test);
}
}
XML看起来像这样:
The XML looks like this:
<xml>
<item>
<name>...</name>
<chapter>...</chapter>
<text>
...
</text>
</item>
<item>
<name>...</name>
<chapter>...</chapter>
<text>
...
</text>
</item>
<item>
<name>...</name>
<chapter>...</chapter>
<text>
...
</text>
</item>
<item>
<name>...</name>
<chapter>...</chapter>
<text>
...
</text>
</item>
<item>
<name>...</name>
<chapter>...</chapter>
<text>
...
</text>
</item>
</xml>
现在,var_dump($test)
将显示以下内容:
As it is right now, the var_dump($test)
prints this:
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { } ...
我该怎么做才能使我的代码循环所有项目并输出值?
What should I do to make my code to loop all the items and prints the value?
推荐答案
尝试一下:
$xml_content = file_get_contents('http://url/feed.xml');
$data = simplexml_load_string($xml_content);
foreach ($data->item as $item) {
var_dump($item->bookname);
}
如果需要,还可以将整个$ item强制转换为数组:
You can also cast whole $item to array if you need:
foreach ($data->item as $item) {
$itemArray = (array) $item;
var_dump($itemArray);
}
您在转储对象时,需要首先将to转换为字符串以返回文本值.
另外,我不认为第二个foreach
在做什么或需要做的事情,因此我将其删除.
You were dumping objects, when you need to cast the to string first to return the text value.
Also, I do not think the second foreach
was doing anything or needed, so I removed it.
这篇关于使用SimpleXML从XML获取多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文