简体   繁体   中英

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. Exapmle : IN row 1,recomnend =2 will read the row that id=2 and print to JSON file that values : 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

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:

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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