如何将CSV转换为JSON需要在CSV文件中的一行将导出一个文件JSON [英] How to convert CSV to JSON with requires one line in CSV file will export one file JSON

查看:677
本文介绍了如何将CSV转换为JSON需要在CSV文件中的一行将导出一个文件JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,需要您的帮助!
我想将CSV转换为JSON,CSV中有1行,导出1个文件JSON(JSON的内容是CSV行的内容,JSON的名称是该行的ID)。
我尽量做,但它只显示和下载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);

?>



推荐答案

因此,您有一个标题为CSV文件。

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

转换为关联数组:

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

要生成文件:

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

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

 }

这里循环计数器 $ index

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

有关

  • array_map
  • str_getcsv
  • file_put_contents

如果您确实需要其他内容,请在下次写下更准确的问题。

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

这篇关于如何将CSV转换为JSON需要在CSV文件中的一行将导出一个文件JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆