Use PHP Simple HTML DOM Parser to find the table cell and get the contents of the next brother

I am trying to use PHP Simple HTML DOM Parser to capture the HTML file of an external file. The file contains a table, and the goal is to find a suitable cell with specific data contents, and then get the following sibling cell data. This data must be placed in a PHP variable.

Based on the research and information found in articles such as How to parse and process HTML / XML using PHP? , Grabbing the href attribute of element A , Data scrambling: PHP Simple HTML DOM Parser and, of course, PHP Simple HTML DOM Parser Manual I got some results, but I'm afraid I'm wrong.

The row of the table is as follows:

<tr>
<td>fluff</td>  
<td>irrelevant</td> 
<td>etc</td>   
<td><a href="one">Hello world</a></td>                        
<td>123.456</td> 
<td>fluff</td>          
<td>irrelevant</td>   
<td>etc</td>
</tr>

What I'm trying to do is find a table cell that contains "Hello world" and then get the number from the next td cell. The following code finds this table cell and echoes its contents, but my attempts to use it as a guide to get the next cell data failed ...

$html = file_get_html("http://site.com/stuff.htm");
$e = $html->find('td',0)->innertext = 'Hello world';
echo $e;

, 123.456 - PHP.

!

+5
2

, DOMXPath. .

:

<?php

$html = <<<EOF
<tr>
<td>fluff</td>  
<td>irrelevant</td> 
<td>etc</td>   
<td><a href="one">Hello world</a></td>                        
<td>123.456</td> 
<td>fluff</td>          
<td>irrelevant</td>   
<td>etc</td>
</tr>
EOF;


// create empty document 
$document = new DOMDocument();

// load html
$document->loadHTML($html);

// create xpath selector
$selector = new DOMXPath($document);

// selects the parent node of <a> nodes
// which content is 'Hello world'
$results = $selector->query('//td/a[text()="Hello world"]/..');

// output the results 
foreach($results as $node) {
    echo $node->nodeValue . PHP_EOL;
}
+4

html dom:

$str = "<table><tr>
<td>fluff</td>  
<td>irrelevant</td> 
<td>etc</td>   
<td><a href=\"one\">Hello world</a></td>                        
<td>123.456</td> 
<td>fluff</td>          
<td>irrelevant</td>   
<td>etc</td>
</tr></table>";

$html = str_get_html($str);

 $tds = $html->find('table',0)->find('td');
 $num = null;
 foreach($tds as $td){

     if($td->plaintext == 'Hello world'){

        $next_td = $td->next_sibling();
        $num = $next_td->plaintext ;    
        break; 
     }
 }

 echo($num);
+2

All Articles