Convert a CSV to JSON with PHP

Imagine a data list dumped in a plain text file (e.g: CSV) and you need to convert it to JSON format. You could use this simple php script to do such task.

It's the simplest version but from here you can customize it to fit your requeriments.

Usage:

php script_name.php file_to_convert.csv > result.json

The script:

$csv = file_get_contents( $argv[1] );
$csv = explode("\n", trim($csv) );

foreach ( $csv as &$line )
{
$line = trim( $line );
}

print json_encode($csv);

This example covers a "single column" CSV file. If you want to add several columns you only need to add an explode with the separator character, be comma, somicolon or tab.