如何使用PHP DOM查询从HTML表中选择文本? [英] How to select text from HTML table using PHP DOM query?

查看:133
本文介绍了如何使用PHP DOM查询从HTML表中选择文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从使用PHP DOM查询的HTML表格单元格中获取文本?

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

HTML表格是:

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

编辑:用这个代替

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

这篇关于如何使用PHP DOM查询从HTML表中选择文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆