why does find('tr')[0]; get table row 2 instead of table row 1 ?
This is my html all tables have the same class and layout.
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><b>hi</b></td>
</tr>
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td>Good</td>
<td><a>Date</a></td>
</tr>
</tbody>
</table>
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><b>hi</b></td>
</tr>
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td>Good</td>
<td><a>Date</a></td>
</tr>
</tbody>
</table>
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><a>hi</a></td>
</tr>
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td>Good</td>
<td><a>LINK</a></td>
</tr>
</tbody>
</table>
This is my php
<?php
include("simpleHtmlDom/simple_html_dom.php");
$html = new simple_html_dom();
// Load a file
$html->load_file('http://mySite.net/');
foreach($html->find('table[class=tablemenu]') as $element){
$Link = $element->find('tr')[0]->find('td')[4]->find('a')[0];
echo($Link->text());
echo '<br />';
}
?>
At first to get the word 'Date' i tried
$Link = $element->find('tr')[1]->find('td')[4]->find('a')[0];
But that didn't work, it said undefined index.
Then i tried this just messing around and it works
$Link = $element->find('tr')[0]->find('td')[4]->find('a')[0];
This gets the word Date for some reason. I don't understand why, i do need that but although it works - i now can't access table row 1. to grab the word say "hi".
I see two one issues:
Your first <tr>
only has 2 <td>
s, so $element->find('tr')[0]->find('td')[4]
should throw an exception.
Edit OP fixed pasted code.
Fix your markup. You're not properly closing your <tr>
elements:
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><b>hi</b></td>
</tr> <!-- close this! --->
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td><a>Date</a></td>
</tr> <!-- close this! --->
</tbody>
</table>
There is wrong indexing
because you are not closing the tr tags
properly
the link should be on first index instead of zeroth index
$Link = $element->find('tr')[1]->find('td')[4]->find('a')[0];
To print
hi try
echo $element->find('tr')[0]->find('td')[1]->find('b')[0]->text();
Full code
foreach($html->find('table[class=tablemenu]') as $element){
$Link = $element->find('tr')[1]->find('td')[4]->find('a')[0];
echo($Link->text());
echo '<br />';
echo $element->find('tr')[0]->find('td')[1]->find('b')[0]->text();
}
If the above not works then find tr
in tbody
like
$Link = $element->find('tbody')->find('tr')[1]->find('td')[4]->find('a')[0];
Also for debugging, try this
foreach($html->find('table[class=tablemenu]') as $element){
echo '<pre>';
var_dump($element);// find the object here
echo '</pre>';
}