表:
<table class="secondary">
<tr><td>BB:</td><td>112</td></tr>
<tr><td>CC:</td><td>99</td></tr>
<tr><td>DD:</td><td>1</td></tr>
</table>
例如,我想获得此表的第三行。
我知道如何使用ID从div标签获取值,例如:
$doc = new DomDocument();
$doc->loadHTMLFile('http://www.results.com');
$thediv = $doc->getElementById('result');
echo $thediv->textContent;
但我们如何从表格行标签中获取值?
答案 0 :(得分:0)
您可以使用DomXpath http://php.net/manual/en/class.domxpath.php
(假设这个例子,你的表是页面上第一个表格为class =&#34; secondary&#34;)
例如:
<?php
$doc = new DomDocument();
$doc->loadHTMLFile("filename.html");
$xpath = new DomXpath($doc);
$row = $xpath->query('//table[@class="secondary"][1]/tr[3]')->item(0);
// Get the html of the third row:
echo $doc->saveHTML($row);
// Get the values from the td's for the third row
foreach ($row->childNodes as $td) {
echo sprintf("nodeName: %s, nodeValue: %s<br>", $td->nodeName, $td->nodeValue);
}