XPath ile meta açıklaması etiketi almak

3 Cevap php

Ben içerik açıklamasını ve anahtar kelimeleri etiket içerik gerekir. Bu kodu vardır, ama bir şey yazmayın. Fikir?

$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;
}

3 Cevap

Sen @ (aşağıya bakınız) özellik ismi ile takip ve özellikleri için doğrudan sorgu kullanarak özelliklerini başvuruda bulunabilir; XPath sorgusu neredeyse yoktu.

// 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;
    }
}

İki sorun var. Eğer başa eklemek gerekir, böylece ilk isim bir niteliktir @

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

Yazdırmak için bir şey yok yani ikinci, düğümlerin hepsi boş.

Öznitelik değerini yazdırmak için, bunu,

foreach($nodes as $node){
  $attr = $node->getAttribute('content');
  print $attr;
}

Eğer gibi herhangi bir boşluk ve girinti olmadan hattında EOD; koymak emin olun:

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

EOD;