Html dom parser php table

110 views Asked by At

Here is my Table

Grapes    1     25     25
Mangoes   2     30     60
Apple     5     10     50

And my Html code for the above table is

<table>
<tr>
<td><font>Grapes</font></td>
<td><font>1</font></td>
<td><font>25</font></td>
<td><font>25</font></td>
</tr>
<tr>
<td><font>Mangoes</font></td>
<td><font>2</font></td>
<td><font>30</font></td>
<td><font>60</font></td>
</tr>
<tr>
<td><font>Apple</font></td>
<td><font>5</font></td>
<td><font>10</font></td>
<td><font>50</font></td>
</tr>
</table>

the above table is 4th table in my html code

my php code is

<?php
include('simple_html_dom.php');
$result = curl_exec($ch);
curl_close($ch);
$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;
@$src->loadHTML($result);
$xpath = new DOMXPath($src);
$values=$xpath->query('//table[4]//tr');

foreach($values as $value)
{
$rowdata = str_replace(">"," ",$value->nodeValue);
$n = explode("\n", $rowdata);
print_r($n);
}

Here $result holds the html code coming from curl execution

and my output is

Array ( [0] => Grapes12525 [1] => ) Array ( [0] => Mangoes23060 [1] => ) Array ( [0] => Apple51050 [1] => )

But i want output as

Array ( [0] => Grapes [1] => 1 [2] => 25 [3] => 25 ) Array ( [0] => Mangoes [1] => 2 [2] => 30 [3] => 60 ) Array ( [0] => Apple [1] => 5 [2] => 10 [3] => 50 )

i have tried with

$values=$xpath->query('//table[4]//tr//td');

but this is printing each value as array

is there any method where we can get the child elements inside for loop for example only td's inside parent tr or any other way to achieve this

Please help me in getting this

Thank you

1

There are 1 answers

0
venca On

I would try:

$rowdata = explode(' ', $value->textContent);

Text content should be whole texts of tr children separated by space.

If this would not working. Do another xpath query in foreach loop with //td and $value as context node.