0

i found this code for csv row as a 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");

how to create each csv row as a separate json file in php

csv row to json file

Prashant
  • 143
  • 1
  • 1
  • 7
  • 1
    Please go read [ask]. We expect you to make a reasonable effort upfront here - not just to ask “how to”. Show us what you tried please. – 04FS Nov 04 '19 at 14:25

1 Answers1

1

Soultion simplified:

while($csv_line = fgetcsv($fp,1024)) {
    $json = [
        'id' => $csv_line[0],
        'product_id' => $csv_line[1],
        'title' => $csv_line[2],
        'outline' =>  $csv_line[3],
    ];
    // use any other naming approach that you want
    file_put_contents('file_' . $csv_line[0] . '.json', json_encode($json));
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64