-1

考虑以下代码:

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

使用 php 和 DOM/xPath,我将如何提取日期值?

4

2 回答 2

0

如果您只想要日期,则此 xpath 将全部返回:

//meta[@itemprop = "date"]/@content
于 2013-06-28T17:01:43.533 回答
0

这应该可以帮助您入门:

<?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!";
}
?>

将导致:

[meta]content = 2013-06-28
itemprop = date
[meta]content = 2013-06-27
itemprop = date
[meta]content = 2013-06-25
itemprop = date
于 2013-06-28T17:02:16.383 回答