-1

Considering the following code:

<div class="item">
  <meta content="2013-06-28" itemprop="date">
</div>
<div class="item">
  <meta content="2013-06-27" itemprop="date">
</div>
<div class="item">
  <meta content="2013-06-25" itemprop="date">
</div>
...

Using php and DOM/xPath, how would I extract the date values?

rdvn
  • 13
  • 5
  • What code have you tried so far? – chrislondon Jun 28 '13 at 16:46
  • `$itemprops = $xpath->query("//@itemprop"); foreach ($itemprops as $itemprop) { $name = $itemprop->nodeValue; $value = $itemprop->nodeValue; }` // $name is correct but $value is empty. Also tried getting value through parentNode, getAttribute but just cant get it right. – rdvn Jun 28 '13 at 16:52
  • Provide a working code.example in your question that shows - when exectued - your problem. – hakre Jun 29 '13 at 00:39
  • Possible duplicate of: [How to extract a node attribute from XML using PHP's DOM Parser](http://stackoverflow.com/q/3993302/367456) – hakre Jun 29 '13 at 09:36

2 Answers2

0

If you just want the dates, this xpath will return them all:

//meta[@itemprop = "date"]/@content
Will Goring
  • 1,040
  • 1
  • 7
  • 18
0

This should help get you started:

<?php
$html = <<< ENDL
<div class="item">
  <meta content="2013-06-28" itemprop="date">
</div>
<div class="item">
  <meta content="2013-06-27" itemprop="date">
</div>
<div class="item">
  <meta content="2013-06-25" itemprop="date">
</div>  
ENDL;

$doc = new DomDocument();
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);

$metas = $xpath->query("*/div[@class='item']/meta");
if(count($metas)) {
  foreach($metas as $key => $element) {
      echo "[{$element->nodeName}]";
      foreach($element->attributes as $attrName => $attrValue) {
          echo "$attrName = $attrValue->nodeValue<br>";
      }
  }
} else {
  echo "No metas found!";
}
?>

Will result in:

[meta]content = 2013-06-28
itemprop = date
[meta]content = 2013-06-27
itemprop = date
[meta]content = 2013-06-25
itemprop = date
Rob W
  • 9,134
  • 1
  • 30
  • 50