我要解析下面的RSS,例如:
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:x-wr="http://www.w3.org/2002/12/cal/prod/Apple_Comp_628d9d8459c556fa#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:x-example="http://www.example.com/rss/x-example" xmlns:x-microsoft="http://schemas.microsoft.com/x-microsoft" xmlns:xCal="urn:ietf:params:xml:ns:xcal" version="2.0">
<channel>
<item>
<title>About Apples</title>
<author>David K. Lowie</title>
<x-trumba:customfield name="description">This is the description about apples</xCal:customfield>
<x-trumba:customfield name="category">Fruits,Food,Apple</xCal:customfield>
</item>
<item>
<title>About Oranges</title>
<author>Marry L. Jones</title>
<x-trumba:customfield name="description">This is the description about oranges</xCal:customfield>
<x-trumba:customfield name="category">Fruits,Food,Orange</xCal:customfield>
</item>
</channel>
</rss>
在PHP中,我只知道如何读取前两个节点,如:
$rss = new DOMDocument();
$rss->load( "http://www.example.com/books.rss" );
foreach( $rss->getElementsByTagName("item") as $node ) {
echo $node->getElementsByTagName("title")->item(0)->nodeValue,
echo $node->getElementsByTagName("author")->item(0)->nodeValue,
}
但是,这些是问题:
<x-trumba:customfield name="description">This is the description about apples</xCal:customfield>
<x-trumba:customfield name="category">Fruits,Food,Apple</xCal:customfield>
请帮助:
<x-trumba:customfield name="description">
?(我无法更改RSS来源,因为它不受我的控制。)
请帮助。
答案 0 :(得分:0)
您的XML无效,未定义'x-trumba'前缀,并且元素的结束标记使用'xCal'前缀,引用urn:ietf:params:xml:ns:xcal
。
因此,用'xCal'替换开始标记的前缀并修复'author'的结束标记会使XML有效。
然后可以注册xCalendar命名空间并使用Xpath来获取自定义字段内容:
$rss = new DOMDocument();
$rss->load( "http://www.example.com/books.rss" );
$xpath = new DOMXpath($rss);
$xpath->registerNamespace('x', 'urn:ietf:params:xml:ns:xcal');
foreach( $xpath->evaluate("//item") as $item ) {
echo $xpath->evaluate('string(title)', $item), "\n";
echo $xpath->evaluate('string(x:customfield[@name="description"])', $item), "\n";
}
输出:
About Apples
This is the description about apples
About Oranges
This is the description about oranges
Xpath表达式使用条件([@name="description"]
)来过滤customfield
个元素节点。