从RSS提要中提取特定条目[PHP]
问题描述:
因此,我有一个RSS提要,其中包含每个条目的变体。我想要做的只是获取包含特定部分文本的条目。从RSS提要中提取特定条目[PHP]
例如:
<item>
<title>RADIO SHOW - CF64K - 05-20-10 + WRAPUP </title>
<link>http://linktoradioshow.com</link>
<comments>Radio show from 05-20-10</comments>
<pubDate>Thu, 20 May 2010 19:12:12 +0200</pubDate>
<category domain="http://linktoradioshow.com/browse/199">Audio/Other</category>
<dc:creator>n0s</dc:creator>
<guid>http://otherlinktoradioshow.com/</guid>
<enclosure url="http://linktoradioshow.com/" length="13005" />
</item>
<item>
<title>RADIO SHOW - CF128K - 05-20-10 + WRAPUP </title>
<link>http://linktoradioshow.com</link>
<comments>Radio show from 05-20-10</comments>
<pubDate>Thu, 20 May 2010 19:12:12 +0200</pubDate>
<category domain="http://linktoradioshow.com/browse/199">Audio/Other</category>
<dc:creator>n0s</dc:creator>
<guid>http://otherlinktoradioshow.com/</guid>
<enclosure url="http://linktoradioshow.com/" length="13005" />
</item>
我只想显示包含字符串CF64K
结果。虽然这可能是非常简单的正则表达式,但我似乎无法将自己的头脑理解为正确。我总是看起来只能显示字符串“CF64K”,而不是围绕它的东西。
在此先感谢。
答
我在猜测(因为您向我们展示了您试图解析的数据,而不是您试图解析的数据),问题在于您尝试使用正则表达式解析XML。不要,它不适合它。
使用RSS解析器。使用它提供的API循环条目。检查它们是否符合您的要求(使用简单的字符串匹配,而不是正则表达式)。处理那些做的,并跳回那些没有的循环的顶部。
答
如果你需要的是一个简单的字符串匹配,那么你可以使用XPath:
$rss = simplexml_load_file($url);
foreach ($rss->xpath('//item[contains(title, "CF64K")]') as $item)
{
print_r($item);
}
否则,你可以在项目环和手动过滤它们
$rss = simplexml_load_file($url);
foreach ($rss->xpath('//item') as $item)
{
if (!preg_match('#CF64K#i', $item->title))
{
continue;
}
print_r($item);
}