使用xpath获取元描述标记

tur*_*bod 15 php xpath

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

$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;
}
Run Code Online (Sandbox Code Playgroud)

sal*_*the 30

您可以使用@属性名称引用属性(参见下文),您可以直接查询属性; 你的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;
    }
}
Run Code Online (Sandbox Code Playgroud)