简体   繁体   中英

Export row from CSV file to JSON

I want to export a row in CSV file to JSON file with require : 1 line in CSV export 1 file JSON. I success to export file,but can't filter the row that i want to export. Can anyone help me?

 <?php

header('Content-type: application/json');

$feed = 'jsondata_palpad.csv';

$keys = array();
$newArray = array();

function csvToArray($file, $delimiter) { 
  if (($handle = fopen($file, 'r')) !== FALSE) { 
    $i = 0; 
    while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { 
      for ($j = 0; $j < count($lineArray); $j++) { 
        $arr[$i][$j] = $lineArray[$j]; 
      } 
      $i++; 
    } 
    fclose($handle); 
  } 
  return $arr; 
} 

$data = csvToArray($feed, ',');

$count = count($data) - 1;
$labels = array_shift($data);  


foreach ($labels as $label) {
  $keys[] = $label;
}


$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
  $data[$i][] = $i;
}


for ($j = 0; $j < $count; $j++) {
 $d = array_combine($keys, $data[$j]);
  $newArray[$j] = $d;
}

//Xuat file JSON
for ($i = 0; $i < 5; $i++) {
    $json = json_encode($newArray[$i]);
    echo $json . "<br />\n";    
    $filename = $data[$i][1] . ".json";
    echo $filename . "<br />\n";
    //echo "title[" . $data[$i][4] . "]";
    $handle = fopen("./" . $filename, "w");
    fwrite($handle, $json);
    fclose($handle);    
}

?>

If recommend = 2,it will export line whre id=2. I want to export id,product_id,title,outline to JSON file.This is sample JSON file: http://img839.imageshack.us/img839/5277/21527799.png This is CSV file : http://img690.imageshack.us/img690/1526/43004273.png

You are looping through all 6 lines of the csv file and saving them to the JSON file:

for ($i = 0; $i < 5; $i++) {
    ...
}

If you know what row number it is you want, don't loop through every row - just call the code inside the loop for that row. For example, if you wanted the 2nd row:

$row_we_want = 1;
$json = json_encode($newArray[$row_we_want]); 
$filename = $data[$row_we_want][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);  

If you are unsure about which row it is and need to check each one, you could do so in the loop:

for ($i = 0; $i < 5; $i++) {
    if (some_condition) {
         $json = json_encode($newArray[$i]); 
        $filename = $i][1] . ".json";
        $handle = fopen("./" . $filename, "w");
        fwrite($handle, $json);
        fclose($handle); 
    }
}

Also it might be worth replacing 5 in your loop with the length of the array using the count function if it is not always a fixed length.

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