使用 xpath 获取元描述标记

2022-08-30 20:52:42

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

$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;
}

答案 1

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

// 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;
    }
}

答案 2

你有两个问题。首先,name 是一个属性,因此您需要在 @,

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

其次,节点都是空的,因此没有要打印的内容。

要打印属性值,请执行以下操作:

foreach($nodes as $node){
  $attr = $node->getAttribute('content');
  print $attr;
}

推荐