5

如何使用in从HTML文件中提取信息DOMDocumentPHP

我的HTML页面有一个源,里面有这部分

这是我需要处理的页面中的第三个表:

 <table>
 <tbody>
 <tr>
   <td>A</td>
   <td>B</td>
   <td>C</td>
   <td>D</td>
</tr>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
  <td>4</td>
</tr>
</tbody>
</table>

如果我的使用要求我显示带有 B 和 D 的行,我应该如何提取该表的第一行并使用 DOMDocument 打印它?

4

2 回答 2

19

这样就可以了,它只是抓取第三个表,循环遍历行并检查第二列BD第四列中的和。如果找到,它会打印出每一列的值,然后停止循环。

$dom = new DOMDocument();
$dom->loadHTML(.....);

// get the third table
$thirdTable = $dom->getElementsByTagName('table')->item(2);

// iterate over each row in the table
foreach($thirdTable->getElementsByTagName('tr') as $tr)
{
    $tds = $tr->getElementsByTagName('td'); // get the columns in this row
    if($tds->length >= 4)
    {
        // check if B and D are found in column 2 and 4
        if(trim($tds->item(1)->nodeValue) == 'B' && trim($tds->item(3)->nodeValue) == 'D')
        {
            // found B and D in the second and fourth columns
            // echo out each column value
            echo $tds->item(0)->nodeValue; // A
            echo $tds->item(1)->nodeValue; // B
            echo $tds->item(2)->nodeValue; // C
            echo $tds->item(3)->nodeValue; // D
            break; // don't check any further rows
        }
    }
}
于 2013-07-12T11:21:58.213 回答
0

这段代码经过我的测试享受它

$table = "<table>
 <tbody>
 <tr>
   <td>A</td>
   <td>B</td>
   <td>C</td>
   <td>D</td>
</tr>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
  <td>4</td>
</tr>
</tbody>
</table>";
$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="utf-8"?>' . $table);
$rows =$doc->getElementsByTagName('tr');
$tds= $doc->getElementsByTagName('td');
$ths= $doc->getElementsByTagName('th');
foreach ($ths as $th) {
echo "<p> th  = ".$th." </p>";
}
foreach ($tds as $td) {
echo "<p> td  = ".$td." </p>";
}
于 2017-06-08T10:42:59.863 回答