Kunal Kunal - 1 month ago 6
PHP Question

How to get td data from a table in PHP

I am currently stuck at this problem right now where I don't seem to have any idea how to implement this. I have this table which is populated from a csv file in php and I want to get the data logged in order to calculate the daylight hours.

How can I get the data from the td "dateLogged", I did that in jquery before using children but I do not seem to be able to do that in php

//print out uploaded file.csv
echo "<html><body><table BORDER=1>\n\n";
echo " <tr><th>AvgCrown</th><th>MinCrown</th><th>MaxCrown</th><th>dateLogged</th><th>DaylightHours</th></tr>";
$f = fopen("./uploads/" . $_FILES["uploadedfile"]["name"], "r");

while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<td>" . calcDaylight() . "</td>";

echo "<tr>\n";


}
fclose($f);
echo "\n</table></body></html>";


Here is a sample how the table looks like

Here is a sample how the table looks like
Any help will be most welcome.

Answer

There's no need to parse the HTML if you can just grab the data while you're generating it. Something like this should be all you need:

while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
        // Save the value before you output
        $lastColValue = htmlspecialchars($cell);
        echo "<td>" . $lastColValue . "</td>";
    }
    // If you want to store all log dates in an array:
    $logDates[] = $lastColValue;
    // Or if you want to do something with that value in calcDaylight:
    echo "<td>" . calcDaylight( $lastColValue ) . "</td>";
    echo "<tr>\n"; 
}
fclose($f);

Incidentally, if you do find you need to parse the HTML and are only familiar with jQuery, this library may strike your fancy:

http://code.google.com/p/phpquery/

Comments