簡體   English   中英

(PHP5)使用PHP DOM或Regex從HTML中提取標題標記和RSS源地址

[英](PHP5) Extracting a title tag and RSS feed address from HTML using PHP DOM or Regex

我想從給定的URL獲取標題標記和RSS提要地址(如果有的話),但到目前為止我使用的方法根本不起作用。 我已經設法通過使用preg_match和正則表達式來獲取標題標簽,但我似乎無法獲得RSS源地址。

($ webContent保存網站的HTML)

我已將我的代碼復制到下面以供參考......

`//獲取標題標簽preg_match('@(。*)@ i',$ webContent,$ 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];`

我一直在讀這里使用正則表達式不是最好的方法嗎? 希望有人可以幫我一把:-)

謝謝。

一種方法

$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
}

要使用“application / rss + xml”類型獲取所有鏈接標記的href屬性,您將使用此XPath:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM