Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

php - How to convert CSV to JSON with requires one line in CSV file will export one file JSON

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);

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So you have a titled CSV file.

To read it, first convert the rows into an array:

 $csv = array_map("str_getcsv", file($filename));
 $head = array_shift($csv);

For conversion into an associative array:

 $csv = array_map("array_combine", array_fill(0, count($csv), $head), $csv);

To generate the files:

 foreach ($csv as $index => $row) {

     file_put_contents("$index.json", json_encode($row));

 }

Here the loop counter $index is used for generating the filenames.

See the manual for explanations on:

If you did want something else, write a more precise question next time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...