Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Created June 9, 2018 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cereal-s/eb1e2323d1e018e452838a3007b02999 to your computer and use it in GitHub Desktop.
Save cereal-s/eb1e2323d1e018e452838a3007b02999 to your computer and use it in GitHub Desktop.
Split CSV columns
<?php
// Usage:
// php split.php < input.csv > output.csv
// CSV format example:
// street,"city, state",zip
// "3526 HIGH ST","SACRAMENTO, CA",95838
// "51 OMAHA CT","SACRAMENTO, CA",95823
// "2796 BRANCH ST","SACRAMENTO, CA",95815
// "2805 JANETTE WAY","SACRAMENTO, CA",95815
// "6001 MCMAHON DR","SACRAMENTO, CA",95824
// "5828 PEPPERMILL CT","SACRAMENTO, CA",95841
// "6048 OGDEN NASH WAY","SACRAMENTO, CA",95842
// "2561 19TH AVE","SACRAMENTO, CA",95820
// "11150 TRINITY RIVER DR Unit 114","RANCHO CORDOVA, CA",95670
ini_set('auto_detect_line_endings', TRUE);
$in = fopen('php://stdin', 'r');
$out = fopen('php://stdout', 'w');
while ( ! feof($in)) {
$csv_line = fgetcsv($in);
// skip empty lines
if(empty($csv_line))
continue;
$split = explode(',', $csv_line[1]); // "City, State"
$output = [
$csv_line[0], // Street
trim($split[0]), // City
$csv_line[2], // Zip
trim($split[1]) // State
];
fputcsv($out, $output);
}
fclose($out);
fclose($in);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment