如何解析网页中的元标记

时间:2011-05-06 04:48:56

标签: php meta-tags robots.txt

  

可能重复:
  CodeIgniter: A Class/Library to help get meta tags from a web page?

任何机构都可以编写一个简单的编程,用于检索已找到或未找到的输出 对于元标记,alltags,robots.txt文件

<?php 
$url = 'example.com'; 
$meta = '<meta http-equiv="Content-type" content="text/html; charset=utf-8" />'; 
$contents = file_get_contents($url); 
if(strpos($contents, $meta) !== false) 
{ 
    echo 'found'; 
} 
else 
{ 
    echo 'not found'; 
}

?>

2 个答案:

答案 0 :(得分:1)

你可以:

  1. 使用 file_get_contents 检索原始HTML数据

  2. Tidy HTML代码,使其更具可读性;如果你的网络服务器上没有安装Tidy:

    apt-get install php5-tidy

  3. 使用 DOMDocument

  4. 解析元素

答案 1 :(得分:1)

function get_meta($url)
{
    // Get & Tidy HTML
    $tidy = new tidy();
    $tidy->parseFile($url, array("output-html" => true));
    $tidy->cleanRepair();
    // Parse XML
    $xml = new DOMDocument();
    $xml->loadHTML($tidy);
    $meta_tags = $xml->getElementsByTagName("meta");
    // Put meta informations in an array
    $meta = array();
    foreach($meta_tags as $meta_tag)
    {
        $key = $meta_tag->hasAttribute("http-equiv") ? $meta_tag->getAttribute("http-equiv") : $meta_tag->getAttribute("name");
        $value = $meta_tag->hasAttribute("content") ? $meta_tag->getAttribute("content") : $meta_tag->getAttribute("value");
        $meta[$key] = $value;
    }
    return $meta;
}

print_r(get_meta("http://php.net/manual/fr/tidy.cleanrepair.php"));
相关问题