繁体   English   中英

从CSV文件读取行并导出到JSON

[英]Read row from CSV file and export to JSON

我想将CSV文件导出为JSON文件,要求在“推荐”字段中读取值并写入JSON文件。 范例:在第1行中,recomnend = 2将读取id = 2的行,并打印到值为:id,product_id,title的JSON文件中。

$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

我不知道执行此操作的其他方法,但是以下方法会起作用。 使用此方法意味着您必须使用列索引,而不是其名称。 如果您知道所需值的列索引,那么这应该不是问题,但我只是想提一提:

$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对象,从而可以提取总数并解析对象以提取行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM