2010-05-23 32 views
0

因此,我有一個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」,而不是圍繞它的東西。

在此先感謝。

回答

1

我在猜測(因爲您向我們展示了您試圖解析的數據,而不是您試圖解析的數據),問題在於您嘗試使用正則表達式解析XML。不要,它不適合它。

使用RSS解析器。使用它提供的API循環條目。檢查它們是否符合您的要求(使用簡單的字符串匹配,而不是正則表達式)。處理那些做的,並跳回那些沒有的循環的頂部。

1

如果你需要的是一個簡單的字符串匹配,那麼你可以使用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); 
}