Posts: 366
Name: Steve
Location: Miami, FL, Earth
|
Here's a nifty way to iterate a very large CSV file and import into your DB without loading the whole thing into memory:
PHP Code:
<?php
$len = 4096; $delimiter = ","; $enclosure = "\"";
$conn = mysql_connect(/* connection info */); mysql_query("BEGIN"); try { $lines = new SplFileObject("/home/my/file/path.csv"); foreach ($lines as $line) { $fh = fopen('php://memory', 'rw'); fwrite($fh, $line); rewind($fh); $result = fgetcsv( $fh, $len, $delimiter, $enclosure ); fclose($fh); foreach ($result as &$value) { $value = "'".mysql_real_escape_string($value)."'"; } $values = implode(", ", $result); mysql_query("INSERT INTO my_table(col1, col2, col3, ...) VALUES ({$values})"); } mysql_query("COMMIT"); } catch (Exception $e) { mysql_query("ROLLBACK"); print($e->getMessage()); } ?>
This way, you get each line one at a time as an array, rather than one huge array with the CSV data.
It allows you to parse and handle very large CSV files without running out of memory - I've imported 1.6 GB CSVs (with millions of records) this way!!!
Also has good error handling to either succeed or fail the entire transaction... so you won't get duplicate records if it fails and you have to restart.
Good luck!
__________________
- Steve
President, Please login or register to view this content. Registration is FREE
Last edited by smoseley; 10-15-2010 at 02:49 PM..
|