2011-05-24 99 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