简体   繁体   中英

get value of html table row tag using php

Table:

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

for example I want to get third row of this table.

I know how to get values from div tag using ID, like:

$doc = new DomDocument();
$doc->loadHTMLFile('http://www.results.com');
$thediv = $doc->getElementById('result');
echo $thediv->textContent;

but how can we get the values from table row tag?

You can use DomXpath http://php.net/manual/en/class.domxpath.php

(Assuming for this example that your table is the first table on the page with class="secondary")

For example:

<?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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM