【问题标题】:getting meta tags info using curl and get_meta_tags()使用 curl 和 get_meta_tags() 获取元标记信息
【发布时间】:2011-07-06 06:56:00
【问题描述】:

有没有一种方法可以使用 curl 以便您可以执行与 php 中的 get_meta_tags() 函数等效的操作?专门用于在 php 中使用 curl 以尽可能少的开销获取外部站点的元标记

【问题讨论】:

    标签: php html curl meta-tags


    【解决方案1】:

    有没有办法使用 curl 让你可以做一些相当于 php 中的 get_meta_tags() 函数的事情

    不,我不这么认为。

    最好的方法是获取数据,并使用HTML parser 解析它。或者,user contributed notes in the manual.

    中有几种基于正则表达式的方法

    【讨论】:

    • @Dude 这个答案如何使用 curl 来解析 HTML?
    • OP 没有询问如何解析 HTML。下面的答案使用 Curl 获取元标记信息。如OP所要求的,其结果相当于php中的 get_meta_tags() 函数。像花花公子一样工作。
    • @Dude 不,它使用 curl 来获取数据,然后继续使用 HTML 解析器来解析信息,正如我所建议的那样。我同意这是更好的答案(它可能应该是被接受的答案),但它不会使我的答案错误
    • 不过,它并没有回答这个问题。我的反对票反映了这一点。
    • @Dude 问题是is there a way to use curl such that you can do something that is equivalent to the get_meta_tags() function in php? 正确答案仍然是否。
    【解决方案2】:
    function file_get_contents_curl($url)
    {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    
    $data = curl_exec($ch);
    curl_close($ch);
    
    return $data;
    }
    
    $html = file_get_contents_curl("http://www.example.com");
    
    //parsing begins here:
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $nodes = $doc->getElementsByTagName('title');
    
    //get and display what you need:
    $title = $nodes->item(0)->nodeValue;
    
    $metas = $doc->getElementsByTagName('meta');
    
    for ($i = 0; $i < $metas->length; $i++)
    {
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
    if($meta->getAttribute('language') == 'language');
        $language = $meta->getAttribute('language');
    }
    
    echo "Title: $title". '<br/><br/>';
    echo "Description: $description". '<br/><br/>';
    echo "Keywords: $keywords";
    

    【讨论】:

      猜你喜欢
      • 2014-01-09
      • 2011-11-23
      • 2019-01-25
      • 1970-01-01
      • 2020-02-19
      • 2014-08-09
      • 2011-06-21
      • 2018-01-19
      • 2018-05-25
      相关资源
      最近更新 更多