【问题标题】:How to convert CSV to JSON with requires one line in CSV file will export one file JSON如何将 CSV 转换为 JSON 需要 CSV 文件中的一行将导出一个文件 JSON
【发布时间】:2012-10-25 22:43:18
【问题描述】:

我有一个问题,需要你的帮助! 我想将 CSV 转换为 JSON,并在 CSV 中使用导出 1 个文件 JSON 的 1 行(JSON 的内容是 CSV 行的内容,JSON 的名称是该行的 id)。 我尝试这样做,但它只是显示和下载 JSON。 请给我一个关于这个问题的建议。 感谢您的帮助!

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

?>

【问题讨论】:

标签: php json csv


【解决方案1】:

所以你有一个标题为 CSV 文件。

要读取它,首先将行转换为数组:

 $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 用于生成文件名。

请参阅手册以获取以下说明:

如果你确实想要别的东西,下次写一个更精确的问题。

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2021-05-15
    • 2015-09-16
    • 2019-02-23
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    相关资源
    最近更新 更多