dsavz66262 2016-08-23 07:45
浏览 25
已采纳

如何使用DOMDocument和DOMXPath回显元标题和元标记

Using this function:

function get_tags($adres)
{
    $dom = new domDocument();
    libxml_use_internal_errors(true);
    if (!$dom->loadHTML($adres)) {
        echo "Error";
    } else echo "Load ok";
    $html = new DOMXPath($dom);
   $html->query('//title');
}

I try to get and echo title and keywords, description, robots meta tags using XPath, but don't know how and how must look query for meta tags.

Thanks

  • 写回答

1条回答 默认 最新

  • doudan4834 2016-08-23 07:56
    关注

    To retrieve the title, I use :

    $titles = $xpath->query('/html/head/title');
    foreach ($titles as $title) {
        $return['title'][] = $title->nodeValue;
    }
    

    Because it's possible that the DOM has multiple <title /> tags, though it is not recommended.

    I then parse all the <meta /> tags, as such :

    $metas = $xpath->query('/html/head/meta');
    foreach ($metas as $meta) {
        $name = strtolower($meta->getAttribute('name'));
        if ($name == 'title' && (!isset($return['title']) || $return['title'] == '')) // There is such a thing as <meta name="title" \>
            $return['title'][] = $meta->getAttribute('content');
        if ($name == 'keywords')
            $return['metakw'][] = $meta->getAttribute('content');
        if ($name == 'description')
            $return['metadesc'][] = $meta->getAttribute('content');
        if ($name == 'robots')
            $return['robots'][] = $meta->getAttribute('content');
    }
    

    But I guess it would be possible to use :

    $metas_title = $xpath->query('/html/head/meta[@name="title"]');
    $metas_desc = $xpath->query('/html/head/meta[@name="description"]');
    $metas_kw = $xpath->query('/html/head/meta[@name="keywords"]');
    $metas_robots = $xpath->query('/html/head/meta[@name="robots"]');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)