I'd like to take a CSV file living server-side and display it dynamically as an html table. E.g., this:
Name, Age, Sex "Cantor, Georg", 163, M
should become this:
<html><body><table> <tr> <td>Name</td> <td>Age</td> <td>Sex</td> </tr> <tr> <td>Cantor, Georg</td> <td>163</td> <td>M</td> </td> </table></body></html>
Solutions in any language are welcome.
First the CSV File i.e. Comma separated Text file, will be read using HTML5 FileReader API as String. Then the String will be parsed into Rows and Columns and will be displayed in HTML Table. The HTML Markup consists of a FileUpload control (HTML File Input) and a HTML Button i.e. Upload.
Right click on the table, then select 'Download table as CSV' from the context menu. The extension downloads the HTML tables in MS Excel style CSV format. Images will be show in the CSV file as the source URL.
The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:
<?php echo "<html><body><table>\n\n"; $f = fopen("so-csv.csv", "r"); while (($line = fgetcsv($f)) !== false) { echo "<tr>"; foreach ($line as $cell) { echo "<td>" . htmlspecialchars($cell) . "</td>"; } echo "</tr>\n"; } fclose($f); echo "\n</table></body></html>";
Here is a simple function to convert csv to html table using php:
function jj_readcsv($filename, $header=false) { $handle = fopen($filename, "r"); echo '<table>'; //display header row if true if ($header) { $csvcontents = fgetcsv($handle); echo '<tr>'; foreach ($csvcontents as $headercolumn) { echo "<th>$headercolumn</th>"; } echo '</tr>'; } // displaying contents while ($csvcontents = fgetcsv($handle)) { echo '<tr>'; foreach ($csvcontents as $column) { echo "<td>$column</td>"; } echo '</tr>'; } echo '</table>'; fclose($handle); }
One can call this function like jj_readcsv('image_links.csv',true);
if second parameter is true then the first row of csv will be taken as header/title.
Hope this helps somebody. Please comment for any flaws in this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With