My scenario is,
Read html page content using php
Retrieving the required data from the html using DOM parser concept by using php
Displaying the retrieved data in the same php page (the content as like in html page)
开发者_如何学编程
I have done all 3 steps, but while displaying the data i didn't get my required format, Here is all of my code (html,php):
Html:
<html>
<head>
<title>data</title>
</head>
<body>
<table border='1'>
<tr><th>Place</th><th>Temperature</th></tr>
<tr><td class='date'>25-08-2011</td></tr>
<tr><td class='city'>A</td><td class='temp'>30 c</td></tr>
<tr><td class='city'>B</td><td class='temp'>29 c</td></tr>
<tr><td class='date'>26-08-2011</td></tr>
<tr><td class='city'>A</td><td class='temp'>28 c</td></tr>
<tr><td class='city'>B</td><td class='temp'>28 c</td></tr>
</table>
</body>
</html>
Php code:
<?php
include('simple_html_dom.php');
$html = file_get_html('data.html');
$sdate[0]="";
$city[0]="";
$temp[0]="";
$c=0;
foreach($html->find('td[class=date]') as $e)
{
$sdate[$c]=$e->innertext;
$c=$c+1;
}
$c=0;
foreach($html->find('td[class=city]') as $e)
{
$city[$c]=$e->innertext;
$c=$c+1;
}
$c=0;
foreach($html->find('td[class=temp]') as $e)
{
$temp[$c]=$e->innertext;
$c=$c+1;
}
for($i=0;$i<$c;$i++)
{
echo 'Date:'. $sdate[$i]."<br>";
echo 'City:'.$city[$i] .', Temp:' . $temp[$i]."<br>" ;
}
?>
Output:
Date:25-08-2011
City:A, Temp:30 c
Date:26-08-2011
City:B, Temp:29 c
Date:
City:A, Temp:28 c
Date:
City:B, Temp:28 c
But, I want to print the result like this format,
Date:25-08-2011
City:A, Temp:30 c
City:B, Temp:29 c
Date:26-08-2011
City:A, Temp:28 c
City:B, Temp:28 c
Please anybody help me...
Thanks, Nandha
You need to rewrite your logic. I already did that for you :)
$tree = array();
foreach ($html->find('td') as $e) {
if ($e->class == 'date') {
$date = $e->innertext;
}
if ($e->class == 'city') {
$city = $e->innertext;
}
if ($e->class == 'temp') {
$tree[$date][$city] = $e->innertext;
}
}
Result will be something like this:
Array
(
[25-08-2011] => Array
(
[A] => 30 c
[B] => 29 c
)
[26-08-2011] => Array
(
[A] => 28 c
[B] => 28 c
)
)
Your problem you are printing in a for loop each element in each of the arrays. It continues until the longest array, thus displaying a date, a city and a temp each time.
Try this:
<?php
include('simple_html_dom.php');
$html = file_get_html('data.html');
foreach($html->find('td') as $e)
{
if ($e->class == 'date')
echo 'Date:'.$e->innertext.'<br>';
else if ($e->class == 'city')
echo 'City:'.$e->innertext;
else if ($e->class == 'temp')
echo 'Temp:'.$e->innertext.'<br>';
}
?>
精彩评论