2011-10-09 89 views
-2

可能重複:
Help getting meta title and description如何獲得使用php的網站的標題和描述?

我已經花了一整天就可以了。在網上搜索。在satckoverflow上也看到了一些類似的問題。但我都感到失望。

我想獲得一些php代碼,我可以輸出標題和4-5行的任何網站使用PHP的描述。

+6

當你說明描述時,你是什麼意思? – MeLight

+1

這就是你需要的東西http://stackoverflow.com/questions/6113716/help-getting-meta-title-and-description/6113811#6113811 – Mob

+0

在這種情況下定義「標題」和「描述」。對於HTML頁面中的'title'元素,您可以獲取頁面並使用DOM解析器來提取該標記。 (如果標籤存在於該頁面上,它可能不存在,以及標籤是否正確定義,它可能不是,以及頁面是甚至是HTML,這可能不是,等等)但是什麼是「描述」?你期望得到什麼?如果它是'meta'標籤中的某個東西,那麼期望它不會比'title'標籤更多。 – David

回答

6
<?php 

    $url = "http://www.drquincy.com/"; 

    $fp = fopen($url, 'r'); 
    $content = ""; 
    while(!feof($fp)) { 
     $buffer = trim(fgets($fp, 4096)); 
     $content .= $buffer; 
    } 


    $start = '<title>'; 
    $end = '</title>'; 
    preg_match("/$start(. *)$end/s", $content, $match); 
    $title = $match[1]; 
    $metatagarray = get_meta_tags($url); 
    $keywords = $metatagarray["keywords"]; 
    $description = $metatagarray["description"]; 
    echo " <div><strong>URL: </strong >$url</div> \n"; 
    echo " <div><strong>Title: </strong >$title</div> \n"; 
    echo " <div><strong>Description: </strong >$description</div>\n"; 
    echo " <div><strong>Keywords: </strong >$keywords</div>\n"; 

只要改變網址:)

+0

它不工作...不知道什麼是錯的? – Muddser

+0

現在嘗試,我編輯 – Dzoki

+0

機會是,這不會有你想要的結果。它會工作,但標題可能會是「瀏覽器不支持」或類似的東西。 –

0

有很多方法來解析HTML。首先,你想要的內容本身:

$res = file_get_contents("http://www.google.com"); 

這假定file_get_contents允許訪問uri。 例如,你可能會利用正則表達式:

preg_match("~<title>(.*?)</title>~", $res, $match); 
$title = $match[1]; 

但它會更好地使用DOM解析器。 http://php.net/manual/en/book.xml.php,但如果目標內容不是有效的xml,那可能會有問題。

相關問題