Php 使用xpath获取元描述标记
我需要的内容,描述和关键字标签的内容。我有这个代码,但不写任何东西。想法Php 使用xpath获取元描述标记,php,xpath,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" c
$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;
}
$str=query('/html/head/meta[name=“description”]');
foreach($node作为$node){
打印$node->nodeValue;
}
确保您放置了EOD代码>在没有空格和缩进的行上,如:
$str = <<< EOD
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
EOD;
$str=您有两个问题。首先,name是一个属性,因此需要在@前面加上前缀
$nodes = $xpath->query('/html/head/meta[@name="description"]');
其次,节点都是空的,因此没有要打印的内容
要打印属性值,请执行以下操作:
foreach($nodes as $node){
$attr = $node->getAttribute('content');
print $attr;
}
您可以使用@
和属性名称(见下文)引用属性,并且可以直接查询属性;您的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;
}
}
除了包含/html/head部分,还可以使用双斜杠,这意味着以下节点可以位于代码中的任何位置:
//meta[@name='description']
将得出与以下相同的结果:
/html/head/meta[@name='description']
这其实没什么大不了的,但输入的内容要少一些。最后但并非最不重要的一点,很抱歉恢复了此线程,查询区分大小写。
换句话说,如果您查找meta name=“description”。。。或者“meta name=“keywords”,它将找不到“meta name=“Description”。。。或“meta name=”关键字“…分别。请小心
我可以告诉你,在使用xdom和metatags一段时间后,最终我相信最好的方法是使用这个函数: