turbod turbod - 2 months ago 21x
PHP Question

get meta description tag with 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">


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

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


$dom = new DOMDocument();


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

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


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;