【问题标题】:Read row from CSV file and export to JSON从 CSV 文件中读取行并导出为 JSON
【发布时间】:2012-11-07 03:53:04
【问题描述】:

我想将 CSV 文件导出到 JSON 文件,需要在推荐字段读取值并写入 JSON 文件。示例:IN row 1,recomnend =2 将读取 id=2 的行并打印到 JSON 文件的值:id,product_id,title。

$json = array();

        $json['id'] = $row['id'];
        $json['product_id'] = $row['product_id'];
        $json['title'] = $row['title'];
        $json['outline'] = $row['outline'];
        $recom[] = $json;  
print json_encode($recom);

http://ns0.upanh.com/b6.s33.d3/3a3ebb93a87c5703f673b399d5613ec2_50639320.untitled.png

【问题讨论】:

  • 从这里复制过去:gist.github.com/1185299
  • 你的问题不是很清楚,链接失效了。
  • 意思是:我想从 CSV 导出到 JSON 文件,需要:CSV 文件中的 1 行 --> 1 个文件 JSON,JSON 文件的内容是这样的ns1.upanh.com/b6.s35.d3/…

标签: php json csv


【解决方案1】:

我不知道有什么不同的方法,但以下方法会起作用。使用这种方法意味着您必须使用列索引,而不是它的名称。如果您知道所需值的列索引,这应该不是问题,但我只是想我会提到:

$fp = fopen('test.csv','r') or die("**! can't open file\n\n");
while($csv_line = fgetcsv($fp,1024)) {
    $id = $csv_line[0];
    $product_id = $csv_line[1];
    $title = $csv_line[2];
    $outline = $csv_line[3];        
}
fclose($fp) or die("**! can't close file\n\n");

现在,因为您将拥有多行,我建议您使用以下方法将它们保存到一个 JSON 对象中:

$fp = fopen('test.csv','r') or die("**! can't open file\n\n");
$i = 0;
while($csv_line = fgetcsv($fp,1024)) {
    $i++;
    $json['json_'.$i]['id'] = $csv_line[0];
    $json['json_'.$i]['product_id'] = $csv_line[1];
    $json['json_'.$i]['title'] = $csv_line[2];
    $json['json_'.$i]['outline'] = $csv_line[3];        
}
$json['total_lines'] = $i;
print json_encode($json);
fclose($fp) or die("**! can't close file\n\n");

通过该方法,可以将每一行保存为一个子JSON Object,从而可以拉取总数并通过对象解析拉出行。

【讨论】:

  • 如何将行内容读写到 JSON 文件。示例:如果推荐 = 2,JSON 将内容 id、title、product_id、CSV 文件中第 2 行的大纲。我整天都在尝试,但做不到:(
  • $i 用作计数器,因此从技术上讲,您可以将 if 语句放在 while 循环中。例如:if ($i = 2) { ... }、... 表示您可以在哪里创建 JSON 对象。不过,这并没有完全优化,您可能会更好地使用 fgets 之类的东西来拉取特定行而不是迭代所有行。
  • 我不明白你的意思,你能把你的代码分享给我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多