Skip to content

Instantly share code, notes, and snippets.

@al-the-x
Created March 30, 2012 14:19
Show Gist options
  • Save al-the-x/2251833 to your computer and use it in GitHub Desktop.
Save al-the-x/2251833 to your computer and use it in GitHub Desktop.
Ingesting a big CSV file, one line at a time...
#!/usr/bin/env php
<?php
/**
* Either make this file executable with `chmod +x read.php` or
* run with `php read.php` passing the input file as the first
* argument, e.g. `php read.php data.csv` or `read.php data.csv`.
* If the file contains a header row, add an environment variable,
* like so: `CSV_HEADER_ROW=1 php read.php data.csv`
*/
$file = fopen($argv[1], 'r');
$fields = ( isset($_SERVER['CSV_HEADER_ROW']) ?
fgetscsv($file) : null
);
while ( $values = fgetcsv($file) )
{
if ( $fields ) $values = array_combine($fields, $values);
// Do something with the $values...
}
fclose($file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment