使用 xpath 获取元描述标签 [英] get meta description tag with xpath

查看:34
本文介绍了使用 xpath 获取元描述标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要内容描述和关键字标签内容.我有这个代码,但不要写任何东西.想法?

I need the content the description and the keywords tag content. I have this code, but dont write anything. Idea?

$str = <<< EOD

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta name="description" content="text in the description tag" />

<meta name="keywords" content="text, in, the, keywords, tag" />

</head>

EOD;
$dom = new DOMDocument();

$dom->loadHTML($str);

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('/html/head/meta[name="description"]');

foreach($nodes as $node){
  print $node->nodeValue;
}

推荐答案

您可以使用 @ 后跟属性名称(见下文)来引用属性,并且可以直接查询属性;您的 XPath 查询几乎就在那里.

You can reference the attributes using @ followed by the attribute name (see below), and you can query directly for the attributes; your XPath query was almost there.

// Look for the content attribute of description meta tags 
$contents = $xpath->query('/html/head/meta[@name="description"]/@content');

// If nothing matches the query
if ($contents->length == 0) {
    echo "No description meta tag :(";
// Found one or more descriptions, loop over them
} else {
    foreach ($contents as $content) {
        echo $content->value . PHP_EOL;
    }
}

这篇关于使用 xpath 获取元描述标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆