Jun 05 2008
Importing CSV files with PHP
Attention: this is a technical article.
Sometimes site owners, with almost zero technical knowledge, want a way to save their database then to import them directly from their web application. For this I usualy save every table as CSV file and for import, I parse every csv file and import in the corespondent table.
Saving a CSV is pretty simple:
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | @mkdir('/tmp/folder'); $out = fopen('/tmp/folder/tableName.csv', 'w'); $stmt = $dbh->query('describe tabelName'); $fields = array(); while(($data = $stmt->fetch(PDO::FETCH_NUM))!= false) { $fields[] = $data[0]; } fputcsv($fields); $stmt = $dbh->query('select * from tabelName'); while(($data = $stmt->fetch(PDO::FETCH_NUM) )!= false) { fputcsv($out, $data); } fclose($out); |
If you want to automatically import some CSV files and have some control over the errors, a very simple way to do it is:
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | $handle = fopen('tableName.csv', 'r'); $fields = fgetcsv($handle); $detail = array(); while(($data = fgetcsv($handle))!== false) { $detail[] = $data; } $x = 0; $stock = array(); foreach($detail as $i) { $y = 0; foreach($fields as $z) { $stock[$x][$z] = $i[$y++]; } $x++; } foreach ($stock as $record) { try { $dbh->query(' INSERT INTO '.$table.'('.implode(',',array_keys($record)).') VALUES ("'.implode('","',$record).'") '); } catch (Exception $db_err) { echo $db_err->getMessage().'<br />\n'; } } |
I use this to make offer some simple backup capabilities for clients and it works pretty well. If you have better ideas please let me know.

saved as xml works pretty well :D… never got an error.
generates larger files but is more.. user friendly
One of the reasons that I don’t want to use XML is the file size. Working with a large database (imagine 1Gb of data), CSV is the best option so far.
Point taken:P
I had a table of around 80000 records that generated a 12MB csv file but it was losing some columns of data and I had to save it to a xml file that was around 50MB.. but I got my data intact.
Well is a good last alternative
Sometimes the best solution is the working one. I’ll never say: “This is bad! Use this!”. But always I’m searching for the best solution.
Alternatives are good!