CSV to HTML Table using php

I am trying to take data from my CSV file and use php to display it in an html table, sorted by customer last name. I have tried a couple things and it doesn’t seem to be working.

The output I got is: enter image description here Right now the format is last, first,address,city,district,postal code How would i import this to an html table using php?

using this code.

if( ($handle = fopen( 'input.csv', 'r' )) !== false )
{
    $output = '<table>';
    while( ($data = fgetcsv( $handle )) !== false )
    {
        $output .= '<tr>';
        foreach( $data as $value )
        {
            $output .= sprintf( '<td>%s</td>', $value );
        }
        $output .= '</tr>';
    }
    fclose( $handle );
    $output .= '</table>';
}
echo $output;

Answer

In your last comment you ask for table header so you can write code like below,

echo '<table border="1">';
echo '<thead>';
echo '<tr>';
echo '<th>last</th>';
echo '<th>first</th>';
echo '<th>address</th>';
echo '<th>.....</th>';
echo '<th>......</th>';
echo '<th>.....</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';

    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        $num = count($data);
        echo '<tr>';

        for ($c=0; $c < $num; $c++) {
            if(empty($data[$c])) {
               $value = "&nbsp;";
            } else {
               $value = $data[$c];
            }                
            echo '<td>'.$value.'</td>';

        }
        echo '</tr>';

        $row++;
    }

    echo '</tbody></table>';

Leave a Reply

Your email address will not be published. Required fields are marked *