通过DOMDocument提取表的特定行

fem*_*chi 5 php html-parsing domdocument

如何HTML使用DOMDocumentin 从文件中提取信息PHP

我的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>
Run Code Online (Sandbox Code Playgroud)

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

MrC*_*ode 15

这将做到这一点,它只是抓住了第三个表,遍历行和检查B,并D在第二和第四列.如果找到,它会打印出每个列值然后停止循环.

$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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)