Read CSV File using PHP

Lets write a simple php program to import data from CSV files or read CSV file using PHP. The following program will read the csv file and display output in HTML table format. Once you get the data you can either display it in HTML format or save in your MySql database.

PHP Code

<?php
include( 'FileReader.php' );
include( 'CSVReader.php' );

$reader =& new CSVReader( new FileReader( 'countrylist.csv' ) );
// set the separator as comma
$reader->setSeparator( ',' );
$line = 0; // line tracking

// output
echo '<table cellpadding=2 cellspacing=1 bgcolor="#cdcdcd" border=0>';
while( false != ( $cell = $reader->next() ) ) {
if ( $line == 0 ) {
echo "<tr>\n";
echo "<td style='font: 12px Arial; font-weight: bold' nowrap> # </td>\n";
for ( $i = 0; $i < count( $cell ); $i++ ){
echo "<td nowrap style='font: 12px Arial; font-weight: bold'> Cell {$i}</td>\n";
}
echo "</tr>\n"; 
}
echo "<tr>\n";
echo "<td bgcolor='".( ( $line % 2 ) == 0 ? '#efefef' : '#ffffff' )."' 
style='font: 12px Arial;'>{$line}</td>\n";
for ( $i = 0; $i < count( $cell ); $i++ )
{
echo "<td bgcolor='".( ( $line % 2 ) ==0 ? '#efefef' : '#ffffff' )."' 
style='font: 12px Arial;'>{$cell[$i]}</td>\n";
}
echo "</tr>\n";
$line++;
}
echo '<table>';

?>

All included files and required files are available in the zip file attached here.

Download Code Total Downloads: 2002

Other Related Posts

Export MySQL table to CSV using PHP
Export MySQL table to iCalendar (.ICS) using PHP
Import data from .ICS file to MySQL table
 
Comments
03 December
2013
Tony Flippance
How do you import this back to MYSQL?

EG i use your other script to pull the sql to CSV I've made my changes now i want to bring it all back in
comments powered by Disqus