简体   繁体   中英

How to select text from HTML table using PHP DOM query?

How can I get text from HTML table cells using PHP DOM query?

HTML table is:

<table>
  <tr>
    <th>Job Location:</th>
    <td><a href="/#">Kabul</a>
    </td>
  </tr>
  <tr>
    <th>Nationality:</th>
    <td>Afghan</td>
  </tr>
  <tr>
    <th>Category:</th>
    <td>Program</td>
  </tr>
</table>

I have following query but it doesn't work:

$xmlPageDom = new DomDocument();
@$xmlPageDom->loadHTML($html);
$xmlPageXPath = new DOMXPath($xmlPageDom);
$value = $xmlPageXPath->query('//table td /text()');

get a complete table with php domdocument and print it

The answer is like this:

$html = "<table ID='myid'><tr><td>1</td><td>2</td></tr><tr><td>4</td><td>5</td></tr><tr><td>7</td><td>8</td></tr></table>";

$xml = new DOMDocument();
$xml->validateOnParse = true;
$xml->loadHTML($html);

$xpath = new DOMXPath($xml);
$table =$xpath->query("//*[@id='myid']")->item(0);

$rows = $table->getElementsByTagName("tr");

foreach ($rows as $row) {
    $cells = $row -> getElementsByTagName('td');
    foreach ($cells as $cell) {
        print $cell->nodeValue;
    }
}

EDIT: Use this instead

$table = $xpath->query("//table")->item(0);

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