2011-05-24 102 views
5

我無法從this specific site得到meta描述/標題。獲取元標題和描述

下面是一些代碼:

$file = file('http://www.thegooddrugsguide.com/lsd/index.htm'); 
$file = implode("",$file); 
if (preg_match('/<title>(.*?)<\/title>/is',$file,$t)) $title = $t[1]; 

它的工作原理與其他網站,但與有問題的網站。可能是什麼問題呢?

+7

DO。不。使用。正則表達式。對於。解析。 HTML。 – 2011-05-24 16:34:41

+2

最好是使用DOM API http://www.php.net/manual/en/book.dom.php – 2011-05-24 16:34:45

+0

毒品說不...除非有免費 – 2011-05-24 16:39:18

回答

16

這應該很好地工作:

$doc = new DOMDocument; 
$doc->loadHTMLFile('http://example.com'); 

$title = $doc->getElementsByTagName('title'); 
$title = $title[0]; 

$metas = $doc->getElementsByTagName('meta'); 

foreach ($metas as $meta) { 
    if (strtolower($meta->getAttribute('name')) == 'description') { 
    $description = $meta->getAttribute('value'); 
    } 
} 

更多信息:http://www.php.net/manual/en/book.dom.php

編輯:這個較短的版本也能正常工作,找到描述:

$xpath = new DOMXPath($doc); 
$description = $xpath->query('//meta[@name="description"]/@content'); 
+0

與HTML文檔,並DOM文檔工作,或只是XHTML? – 2011-05-24 16:43:00

+1

@Salman A Both。 – seriousdev 2011-05-24 16:46:43

+0

+1 ... xpath4tw – Hannes 2011-05-24 16:51:12

3
$url = "http://www.thegooddrugsguide.com/lsd/index.htm";  
$tags = get_meta_tags($url); 
$description = $tags["description"]; 
+0

請添加一個desctiption,而不僅僅是代碼 – Jens 2017-09-27 14:16:43