2010-06-16 38 views
4

我想從給定的URL獲得標題標籤和RSS提要地址(如果有的話),但方法)到目前爲止,我用過的根本不工作。我設法通過使用preg_match和一個正則表達式來獲得標題標籤,但是我似乎無法獲取RSS提要地址。(PHP5)使用PHP DOM或Regex從HTML中提取標題標籤和RSS提要地址

($ web內容保存網站的HTML)

我已經複製下面的參考我的代碼...

`//獲取標題標籤 的preg_match('@(。 *)@我」,$網絡內容,$ titleTagArray);

// If the title tag has been found, assign it to a variable 
if($titleTagArray && $titleTagArray[3]) 
$webTitle = $titleTagArray[3]; 

// Get the RSS or Atom feed address 
preg_match('@<link(.*)rel="alternate"(.*)href="(.*)"(.*)type="application/rss+xml"\s/>@i',$webContent,$feedAddrArray); 

// If the feed address has been found, assign it to a variable 
if($feedAddrArray && $feedAddrArray[2]) 
$webFeedAddr = $feedAddrArray[2];` 

我一直在閱讀這裏,使用正則表達式不是最好的方式來做到這一點?希望有人能給我一個這樣的手:-)

謝謝。

回答

0

RegExp遠離最佳解決方案;) 使用feed閱讀器,例如Zend框架的Zend_Feed類。

+3

很好的選擇,如果他是解析RSS源。儘管他正在解析HTML頁面。 – Gordon 2010-06-16 15:18:31

5

一種方法

$dom = new DOMDocument;   // init new DOMDocument 
$dom->loadHTML($html);    // load HTML into it 
$xpath = new DOMXPath($dom);  // create a new XPath 

$nodes = $xpath->query('//title'); // Find all title elements in document 
foreach($nodes as $node) {   // Iterate over found elements 
    echo $node->nodeValue;   // output title text 
} 

要獲得所有鏈接標籤的href屬性與類型的「應用程序/ RSS + XML」你會使用這個XPath:

$xpath->query('//link[@type="application/rss+xml"]/@href'); 
+1

對於更廣泛的Feed類型,您可以使用如下形式:'/ html/head/link [@ rel =「alternate」and @href and(@ type =「application/atom + xml」or @ type =「application/rss + xml「或@ type =」application/rdf + xml「)]/@ href' - 正則表達式會很好,但'或'就足夠了 – salathe 2010-06-16 18:28:14