循环遍历 xml 数据。只得到第一个结果

我不明白为什么这没有在所有孩子中循环。它只显示第一个孩子/结果。任何帮助,将不胜感激 :)


PHP for 循环代码:


$xml = simplexml_load_file('data.xml') or die('Failed to create an object');

  foreach($xml->children() as $xml_node) {          

    echo $xml_node->item->title . ", ";     

    echo $xml_node->item->description . ", ";     

}

数据.xml


<rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0">

<channel>

<title>Reviews</title>

<description>5 Star Reviews</description>


<item>

<title>Review 1 on Google</title>

<description>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis</description>

<pubDate>Wed, 08 Jul 2020</pubDate>

</item>


<item>

<title>Review 2 on Google</title>

<description>Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,</description>

<pubDate>Tue, 07 Jul 2020</pubDate>

</item>


<item>

<title>Review 3 on Google</title>

<description>Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, </description>

<pubDate>Fri, 26 Jun 2020</pubDate>

</item>


<item>

<title>Review 4 on Google</title>

<description>Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio </description>

<pubDate>Fri, 26 Jun 2020</pubDate>

</item>


</channel>

</rss>


RISEBY
浏览 119回答 1
1回答

潇湘沐

您仅获得该rss元素的第一个子元素,即channel的唯一子元素rss。这告诉它只循环一次。您需要指定您希望其子元素channel是多个item元素。请尝试以下方法:$xml = simplexml_load_file('data.xml') or die('Failed to create an object');&nbsp; foreach($xml->channel->children() as $xml_node) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; echo $xml_node->title . ", ";&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; echo $xml_node->description . ", ";&nbsp; &nbsp; &nbsp;}item通过此更改,您可以访问:title和的直接子元素description。
打开App,查看更多内容
随时随地看视频慕课网APP