Report inadequate content

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.


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.


Comments Convert a CSV to JSON with PHP

For PHP5 you can use the function str_getcsv directly
Ok, so I'm a PHP do I specify the csv file?
Cori Cori 12/06/2013 at 16:41

Leave your comment Convert a CSV to JSON with PHP

Log in to Obolog, or create your free blog if you are not registered yet.

User avatar Your name