用PHP处理XML
我已经设法使用PHP创建了一个XML文档。现在我想使用PHP循环遍历xml文档并适当地显示它。这是我已经拥有的代码,但似乎不起作用 PHP循环用PHP处理XML,php,xml,Php,Xml,我已经设法使用PHP创建了一个XML文档。现在我想使用PHP循环遍历xml文档并适当地显示它。这是我已经拥有的代码,但似乎不起作用 PHP循环 <?php $rss2 = simplexml_load_file('food.xml'); print "<h3>XML document processed with PHP</h3>"; foreach ($rss2->xml-&g
<?php
$rss2 = simplexml_load_file('food.xml');
print "<h3>XML document processed with PHP</h3>";
foreach ($rss2->xml->item as $item){
print "Title: ". $item->name."<br>";
print "Link: <a href=".$item->link.">".$item->link."</a><br>";
print "Description: ". $item->description."<br>";
print "<hr />";
}
?>
XML文档
<?xml version="1.0"?>
<xml>
<item>
<name>Food home page</name>
<link>http://www.food.com/</link>
<description>home cooking inspiration</description>
</item>
<item>
<name>Popular recipes</name>
<link>http://www.food.com/recipes-popular</link>
<description>Popular home food recipes</description>
</item>
<item>
<name>Pulled pork</name>
<link>http://www.food.com/recipe/pulled-pork-crock-pot-131018</link>
<description>Crock pot pulled pork recipe</description>
</item>
</xml>
食品主页
http://www.food.com/
家庭烹饪的灵感
流行食谱
http://www.food.com/recipes-popular
流行的家庭食品食谱
拉肉
http://www.food.com/recipe/pulled-pork-crock-pot-131018
锅拉猪肉食谱
任何人的帮助都将不胜感激
谢谢通过使用调试器或在
$rss2
变量上运行var\u dump
,您可以看到$rss2
上唯一的属性被称为项
。我的收获是simplexml以某种方式按元素名对项进行分组,并以类似数组的方式公开它们。然而,如果你想了解更多的话,那很可能是
为了更清晰地循环数据,我建议将For循环编写为foreach($element\u name=>$item)
($element\u name
将保存元素名称,即item
,这在XML模式允许根级别的其他元素的情况下可能很有意义),尽管foreach($rss2->item as$item)
同样有效。重写
foreach ($rss2->xml->item as $item)
到
$rss2已经处于xml标记级别,因为它是顶级标记。实际上,您所说的“xml-xml-item”在您的数据文件中不存在。RSS的文档元素应该是
RSS
,而不是xml
。顺便说一句
foreach ($rss2->item as $item)