从dom对象获取特定数据

时间:2018-01-27 22:35:47

标签: php html dom

这个问题之前是我的问题:get specific data from php cURL

现在这是我的代码:

$html = file_get_contents('https://nolp.dhl.de/nextt-online-public/de/search?piececode=TRACKING_NUMBER');
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('td') as $node) {
    echo $dom->saveHtml($node);
}

我的$ html变量的一部分:

<table>
   <tr>
      <td data-label="Date">xxx</td>
      <td data-label="Location">xxx</td>
      <td data-label="State">xxx</td>
  </tr>
   <tr>
      <td data-label="Date">xxx</td>
      <td data-label="Location">xxx</td>
      <td data-label="State">xxx</td>
  </tr>
   <tr>
      <td data-label="Date">xxx</td>
      <td data-label="Location">xxx</td>
      <td data-label="State">xxx</td>
  </tr>
   <tr>
      <td data-label="Date">xxx</td>
      <td data-label="Location">xxx</td>
      <td data-label="State">xxx</td>
  </tr>
</table>

使用上面的代码,我获得了具有<td>标记的元素的所有值。 但是,如何获取data-label属性=“Date”的所有<td>标记的值?

非常感谢:)

1 个答案:

答案 0 :(得分:0)

尝试:

$html = '<table>
       <tr>
          <td data-label="Date">xD1</td>
          <td data-label="Location">xxx</td>
          <td data-label="State">xxx</td>
      </tr>
       <tr>
          <td data-label="Date">xD2</td>
          <td data-label="Location">xxx</td>
          <td data-label="State">xxx</td>
      </tr>
    </table>';
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('td') as $node) {
    //echo $dom->saveHtml($node);
    if ($node->getAttribute('data-label') == "Date")
    {
      echo $node->nodeValue;
      echo "<br>";
    }
}

<强>输出:

xD1
xD2