获得元标题和描述

joh*_*nny 5 html php meta-tags

我无法从此特定网站获取元描述/标题.

这是一些代码:

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

它适用于其他网站,但不适用于相关网站.可能是什么问题呢?

ser*_*dev 18

这应该工作正常:

$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');
  }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:这个较短的版本也可以找到描述:

$xpath = new DOMXPath($doc);
$description = $xpath->query('//meta[@name="description"]/@content');
Run Code Online (Sandbox Code Playgroud)