且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

rss Xml 命名空间混淆

更新时间:2023-11-27 20:08:10

您必须使用 XPath 来找到正确的节点,然后从中获取值.xpath() 总是返回一个数组,因此您必须编写一个只返回该数组的第一个元素的小函数.

You will have to use XPath to find the right nodes, then get the value out of that. xpath() always returns an array, so you'll have to write a small function that returns only the first element of that array.

要访问命名空间元素,您可以使用 XPath 表达式或 SimpleXML 的 children() 方法.因为parent-guid"包含一个连字符,所以写属性名有点尴尬.

To access namespaced elements, you can either use an XPath expression or SimpleXML's children() method. Because "parent-guid" contains an hyphen, it makes writing the name of the property a bit awkward.

这是一个工作示例:

function attr(SimpleXMLElement $item, $key)
{
    $values = $item->xpath('./jskit:attribute[@key="' . $key . '"]/@value');
    return $values[0];
}

$rss = simplexml_load_string($xml);

foreach ($rss->channel->item as $item)
{
    $permalink   = attr($item, 'permalink');

    // either
    $parent_guid = $item->children('http://purl.org/dc/elements/1.1/')->{'parent-guid'};

    // or (PHP 5.2)
    $parent_guid = $item->children('jskit', true)->{'parent-guid'};

    // or
    $parent_guid = $item->xpath('./jskit:parent-guid');
    $parent_guid = $parent_guid[0];
}