tags:

views:

107

answers:

3

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">

<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;
}
A: 

Make sure that you put EOD; at a line without any spaces and indentation like:

  $str = <<< EOD
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

EOD;
Web Logic
That's good, the error is different!
turbod
A: 

You have two problems. First, name is an attribute so you need to prepend @,

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

Second, the nodes are all empty so there is nothing to print.

To print the attribute value, do this,

foreach($nodes as $node){
  $attr = $node->getAttribute('content');
  print $attr;
}
ZZ Coder
+2  A: 

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;
    }
}
salathe
Thanks. This works.
turbod