Мне нужно содержание, описание и ключевые слова отмечают содержание. Я имею этот код, но ничего не пишу. Идея?
$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 был почти готов.
// 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;
}
}
У вас две проблемы. Во-первых, имя - это атрибут, поэтому вам нужно добавить @,
$nodes = $xpath->query('/html/head/meta[@name="description"]');
Во-вторых, все узлы пусты, поэтому печатать нечего.
Чтобы распечатать значение атрибута, сделайте следующее:
foreach($nodes as $node){
$attr = $node->getAttribute('content');
print $attr;
}
Убедитесь, что вы поставили EOD;
в строке без пробелов и отступов, например:
$str = <<< EOD
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
EOD;