将每个csv行创建为php中的json文件

问题描述 投票:0回答:1

我发现此代码作为对象的csv行

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

如何在php中将每个csv行创建为单独的json文件

csv row to json file

php json csv fgetcsv csvtojson
1个回答
0
投票

简化外观:

while($csv_line = fgetcsv($fp,1024)) {
    $json = [
        'id' => $csv_line[0],
        'product_id' => $csv_line[1],
        'title' => $csv_line[2],
        'outline' =>  $csv_line[3],
    ];
    file_put_contents('file_' . $csv_line[0] . '.json', json_encode($json));
}
© www.soinside.com 2019 - 2024. All rights reserved.