简体   繁体   English

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

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

I want to export CSV file to JSON file,require is read value at recommend field and write to JSON file. 我想将CSV文件导出为JSON文件,要求在“推荐”字段中读取值并写入JSON文件。 Exapmle : IN row 1,recomnend =2 will read the row that id=2 and print to JSON file that values : id,product_id,title. 范例:在第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 http://ns0.upanh.com/b6.s33.d3/3a3ebb93a87c5703f673b399d5613ec2_50639320.untitled.png

I don't know of a different way of doing it, but the following will work. 我不知道执行此操作的其他方法,但是以下方法会起作用。 Using this method means that you have to use the column index, not the name of it. 使用此方法意味着您必须使用列索引,而不是其名称。 This shouldn't be a problem if you know the column index of the values you need, but I just thought I would mention: 如果您知道所需值的列索引,那么这应该不是问题,但我只是想提一提:

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

Now, because you will have multiple rows, I would recommend the following to save them into one JSON object: 现在,因为您将有多行,所以我建议以下内容将它们保存到一个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");

With this method, you can save each row as a sub-JSON Object, making it possible to pull the total number and parse through the objects to pull out the rows. 使用这种方法,您可以将每一行保存为一个子JSON对象,从而可以提取总数并解析对象以提取行。

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

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