Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created June 3, 2011 14:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hubgit/1006465 to your computer and use it in GitHub Desktop.
Save hubgit/1006465 to your computer and use it in GitHub Desktop.
Convert between comma- and tab-separated files
#!/usr/bin/env php
<?php
// note: the file extensions of the input and output files (.csv, .tsv) must be correct
if ($argc < 3) exit(sprintf("Usage: [php] %s 'input-file.ext' 'output-file.ext' [enclosure]\n", escapeshellarg($argv[0])));
list(, $input, $output, $enclosure) = $argv;
if (!$enclosure) $enclosure = '"';
$input_file = fopen($input, 'r') or die('Could not open input file');
$output_file = fopen($output, 'w') or die('Could not open output file');
$input_separator = guess_separator($input);
$output_separator = guess_separator($output);
while (($data = fgetcsv($input_file, 0, $input_separator, $enclosure)) !== false){
fputcsv($output_file, $data, $output_separator, $enclosure);
}
function guess_separator($file){
switch (pathinfo($file, PATHINFO_EXTENSION)){
case 'tsv': return "\t";
case 'csv': default: return ',';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment