Retrieving a specific row of a DOMDocument table

how can I extract information from an HTML file using a DOMDocument in PHP

My HTML page has a source with this part inside

This is my third table on the page I need to work on:

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

If my use asks me to show a row with B and D, how can I extract the first row of this table and print it using DOMDocument?

+4
source share
2 answers

This will do it, it just grabs the third table, iterates over the rows and checks for B and D in the second and fourth columns. If found, it prints each column value, and then stops the loop.

 $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 } } } 
+13
source

this code is checked by me, enjoy it

 $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>"; } 
0
source

Source: https://habr.com/ru/post/1491091/


All Articles