simplexml_load_string - 相同的对象属性

时间:2013-01-10 01:44:38

标签: php xml simplexml

<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

2 个答案:

答案 0 :(得分:2)

对于这个特定情况,我建议通过SimpleXMLElement::xpath functionDocscategory元素作为数组:

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

这给出了您的单个示例项目:

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

完成了。 ;)另见implodeDocs

答案 1 :(得分:1)

修改

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

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

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

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

请参阅Example #4 Accessing non-unique elements in SimpleXML