Reputation: 11
I need to loop through some records within an excel file and output them as headings for an HTML table but I don't know what is the best approach as I am new to PHP.
Each the column headings begins as a Title followed by an index so you have:
Country1, Country2, Country3 ....through to Country50.
I would like to have a more automatic way to retrieve these values rather than stick to the
$result .= "$Country1";
each must also contain the id of the country which should also be converted into an array i.e. The other thing so they do not require to be printed if that's the case, so the results could be
<th id="Country1">Value of Country1</th>
<th id="Country2">Value of Country2</th>
<th id="Country3">Value of Country3</th>
<th id="Country8">Value of Country8</th>
<th id="Country24">Value of Country24</th>
<th id="Country30">Value of Country30</th>
What is the best "code light" approach to doing this?
Regards!
Upvotes: 1
Views: 2030
Reputation: 2277
something like that should work:
<?php
$handle = @fopen("/tmp/myfile.csv", "r");
if ($handle) {
// first line should be the header, we make it an array of strings
if ( ($buffer = fgets($handle, 4096)) !== false )
$headers[] = explode(",", $buffer);
else
echo "Error: empty file...\n";
// second line should be the values, for each line we output the xml markups
while ( ($buffer = fgets($handle, 4096)) !== false )
{
$values[] = explode(",", $buffer);
if( count($headers) != count(values) )
echo "Error: the 2 lines do not have same number of columns...\n";
else
{
for( $i = 0 ; $i < count($headers) ; $i++ )
echo "<th id='".$headers[$i]."'>".$values[$i]."</th>\n";
}
}
else
echo "Error: second line empty...\n";
if ( !feof($handle) )
echo "Erreur: fgets() failed...\n";
fclose($handle);
}
?>
Upvotes: 0