Created
June 3, 2011 14:54
-
-
Save hubgit/1006465 to your computer and use it in GitHub Desktop.
Convert between comma- and tab-separated files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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