I have a problem and need a help from you!
I want to convert CSV to JSON,and 1 line in CSV with export 1 file JSON (JSON’s content is CSV line’s content,and JSON’s name is id of this line).
I try to do,but it’s only display and download JSON.
Please give me a suggestion for this problem.
Thanks for your help!
<?php header('Content-type: application/json'); $feed = 'jsondata_palpad.csv'; $keys = array(); $newArray = array(); function csvToArray($file, $delimiter) { if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; } $i++; } fclose($handle); } return $arr; } $data = csvToArray($feed, ','); $count = count($data) - 1; $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } $keys[] = 'id'; for ($i = 0; $i < $count; $i++) { $data[$i][] = $i; } for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $newArray[$j] = $d; } header("Content-type: application/json"); header("Content-Disposition: attachment; filename=test.json"); header("Expires: 0"); header("Pragma: no-cache"); echo json_encode($newArray); ?>
So you have a titled CSV file.
To read it, first convert the rows into an array:
For conversion into an associative array:
To generate the files:
Here the loop counter
$indexis used for generating the filenames.See the manual for explanations on:
array_mapstr_getcsvfile_put_contentsIf you did want something else, write a more precise question next time.