0
<item>
    <title>Avoid tornado death by spinning backwards</title>
    <link>www.example.com/survival_tips</link>
    <pubDate>Mon, 13 Aug 2043 00:16:21 +0000</pubDate>
    <dc:creator>Helen Hunt</dc:creator>
    <description></description>
    <content:encoded></content:encoded>
    <category domain="post_tag" nicename="surv"><![CDATA[Survival]]></category>
    <category domain="category" nicename="tip"><![CDATA[Tips]]></category>
    <category domain="category" nicename="torn"><![CDATA[Tornados]]></category>
</item>

考虑上面的 XML。我可以通过以下方式轻松访问标题:

$feed = simplexml_load_string($xml);

foreach ($feed->channel->item as $entry) {
     echo $entry->title.", ";
}

我怎样才能为所有<category...>领域做到这一点?(我意识到如果它们被包裹在父<Categories>标签中,我可以做到这一点,但事实并非如此。

预期输出:Survival, Tips, Tornados

4

2 回答 2

2

对于这种特定情况,我建议通过函数Docscategory将元素作为数组获取:SimpleXMLElement::xpath

foreach ($feed->channel->item as $entry) {
    echo $entry->title . ", " . implode(', ', $entry->xpath('category'));
}

这为您的单个示例项目提供了:

Avoid tornado death by spinning backwards, Survival, Tips, Tornados

并做了。;) 另请参阅implodeDocs

于 2013-01-10T13:51:32.897 回答
1

编辑

更新以反映“项目”循环中的迭代

foreach ($feed->channel->item as $entry) {

    $categories = array();
    foreach ($entry->category as $category) {
        $categories[] = (string) $category;
    }

    echo 'In ', $entry->title, ': ', implode(', ', $categories);
}

请参阅示例 #4 访问 SimpleXML 中的非唯一元素

于 2013-01-10T01:48:51.670 回答