【问题标题】:Getting meta title and description获取元标题和描述
【发布时间】:2011-09-01 02:32:39
【问题描述】:

我无法从this specific site 获取元描述/标题。

这里有一些代码:

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

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

【问题讨论】:

  • 做。不是。采用。正则表达式。为了。解析。 HTML。
  • 最好是使用DOM api php.net/manual/en/book.dom.php
  • 对毒品说不...除非有免费的

标签: php html meta-tags


【解决方案1】:
$url = "http://www.thegooddrugsguide.com/lsd/index.htm";    
$tags = get_meta_tags($url);
$description = $tags["description"];

【讨论】:

    【解决方案2】:

    这应该可以正常工作:

    $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');
    

    【讨论】:

    • 嘿,我收到了这个错误:DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: Invalid char in CDATA 0x1F in http://www.thegooddrugsguide.com/lsd/index.htm, line: 1
    • 我也试过example.com,然后我得到这个错误:Cannot use object of type DOMNodeList as array
    • @johnny 刚刚编辑添加 ->item(0)->nodeValue;而不是 [0]。刚刚测试,现在可以使用了
    • 有人再次修改(或者修改没有被批准)...我会写在这里:而不是$title = $title[0];使用$title = $title-&gt;item(0)-&gt;nodeValue;
    • 你应该使用$description = $meta-&gt;getAttribute('content'); 而不是getAttribute('value')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多