JSON数组转换为CSV

时间:2019-03-07 15:40:51

标签: php arrays json csv

我正在尝试将JSON响应转换为CSV文件,但是有关数组的问题 这是CSV的转换代码

$jsonString = file_get_contents("feed.json");
$jsonDecoded = json_decode($jsonString, true);
$json = $jsonDecoded['results'];
jsonToCsv($json, "feed.csv");

function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false) {

    // See if the string contains something
    if (empty($json)) { 
      die("The JSON string is empty!");
    }

    // If passed a string, turn it into an array
    if (is_array($json) === false) {
      $json = json_decode($json, true);
    }

    // If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
    if ($csvFilePath !== false) {
      $f = fopen($csvFilePath,'w+');
      if ($f === false) {
        die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");
      }
    }
    else {
      $boolEchoCsv = true;
      if ($boolOutputFile === true) {
        $boolEchoCsv = false;
      }
      $strTempFile = 'feed' . date("U") . ".csv";
      $f = fopen($strTempFile,"w+");
    }

    $firstLineKeys = false;
    foreach ($json as $line) {
      if (empty($firstLineKeys)) {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
      }

      // Using array_merge is important to maintain the order of keys acording to the first element
      fputcsv($f, array_merge($firstLineKeys, $line));
    }
    fclose($f);

    // Take the file and put it to a string/file for output (if no save path was included in function arguments)
    if ($boolOutputFile === true) {
      if ($csvFilePath !== false) {
        $file = $csvFilePath;
      }
      else {
        $file = $strTempFile;
      }

      // Output the file to the browser (for open/save)
      if (file_exists($file)) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Length: ' . filesize($file));
        readfile($file);
      }
    }
    elseif ($boolEchoCsv === true) {
      if (($handle = fopen($strTempFile, "r")) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
          echo implode(",",$data);
          echo "<br />";
        }
        fclose($handle);
      }
    }

    // Delete the temp file
    unlink($strTempFile);

  }
?>

这是feed.json内容的示例

 {
   "isError":false,
   "messages":[

   ],
   "results":[
      {
         "part_number_key":"DASDSA",
         "buy_button_rank":1,
         "category_id":11,
         "id":123,
         "brand":"brand",
         "vendor_category_id":null,
         "name":"Name",
         "part_number":"part number",
         "sale_price":12.31,
         "currency":"RON",
         "description":"description",
         "url":"https://www.url.com",
         "warranty":12,
         "general_stock":10,
         "weight":"0",
         "status":1,
         "recommended_price":12.19,
         "images":[
            {
               "url":"https://url.com/images.jpg1",
               "display_type":1
            },
            {
               "url":"https://url.com/images.jpg2",
               "display_type":0
            },
            {
               "url":"https://url.com/images.jpg3",
               "display_type":0
            }
         ],
         "characteristics":[
            {
               "id":8937,
               "value":"value"
            },
            {
               "id":8930,
               "value":"value"
            },
            {
               "id":8927,
               "value":"value"
            },
            {
               "id":8928,
               "value":"value"
            },
            {
               "id":5537,
               "value":"value"
            },
            {
               "id":8932,
               "value":"value"
            },
            {
               "id":8934,
               "value":"value"
            },
            {
               "id":8929,
               "value":"value"
            },
            {
               "id":7235,
               "value":"value"
            },
            {
               "id":6556,
               "value":"value"
            },
            {
               "id":5401,
               "value":"value"
            }
         ],
         "attachments":[

         ],
         "vat_id":1,
         "family":{
            "id":1104,
            "name":"NAME",
            "family_type_id":244
         },
         "start_date":[

         ],
         "estimated_stock":10,
         "reversible_vat_charging":false,
         "min_sale_price":11,
         "max_sale_price":200,
         "offer_details":{
            "id":2484194,
            "warranty_type":null,
            "supply_lead_time":14
         },
         "offer_properties":[

         ],
         "product_measurements":[

         ],
         "availability":[
            {
               "warehouse_id":1,
               "id":3
            }
         ],
         "stock":[
            {
               "warehouse_id":1,
               "value":10
            }
         ],
         "handling_time":[
            {
               "warehouse_id":1,
               "value":0
            }
         ],
         "barcode":[

         ],
         "ean":[

         ],
         "commission":{
            "value":"20.0000",
            "type":"percentage",
            "id":"123",
            "priority":"4",
            "created":"2010-01-16 11:25:02"
         },
         "validation_status":[
            {
               "value":9,
               "description":"Approved documentation",
               "errors":null
            }
         ],
         "offer_validation_status":{
            "value":1,
            "description":"Saleable",
            "errors":null
         },
         "ownership":1,
         "best_offer_sale_price":11,
         "best_offer_recommended_price":11,
         "number_of_offers":1
      },
      {
         "part_number_key":"D3129DKQW",
         "buy_button_rank":1,
         "category_id":456,
         "id":123,
         "brand":"Bluedio",
         "vendor_category_id":null,
         "name":"name",
         "part_number":"part number",
         "sale_price":123,
         "currency":"EUR",
         "description":"description",
         "url":"https://url.com",
         "warranty":24,
         "general_stock":1,
         "weight":"0",
         "status":1,
         "recommended_price":12,
         "images":[
            {
               "url":"https://url.com/images.jpg1",
               "display_type":1
            },
            {
               "url":"https://url.com/images.jpg2",
               "display_type":0
            },
            {
               "url":"https://url.com/images.jpg3",
               "display_type":0
            }
         ],
         "characteristics":[
            {
               "id":7774,
               "value":"val"
            },
            {
               "id":7947,
               "value":"val"
            },
            {
               "id":8001,
               "value":"val"
            },
            {
               "id":8937,
               "value":"val"
            },
            {
               "id":8930,
               "value":"val"
            },
            {
               "id":8927,
               "value":"val"
            },
            {
               "id":8928,
               "value":"val"
            },
            {
               "id":5537,
               "value":"val"
            },
            {
               "id":8932,
               "value":"val"
            },
            {
               "id":8934,
               "value":"val"
            },
            {
               "id":8929,
               "value":"val"
            },
            {
               "id":7235,
               "value":"val"
            },
            {
               "id":6556,
               "value":"val"
            },
            {
               "id":5401,
               "value":"val"
            }
         ],
         "attachments":[

         ],
         "vat_id":1,
         "family":{
            "id":123456,
            "name":"Name",
            "family_type_id":244
         },
         "start_date":[

         ],
         "estimated_stock":144,
         "reversible_vat_charging":false,
         "min_sale_price":11,
         "max_sale_price":200,
         "offer_details":{
            "id":242414,
            "warranty_type":null,
            "supply_lead_time":14
         },
         "offer_properties":[

         ],
         "product_measurements":[

         ],
         "availability":[
            {
               "warehouse_id":1,
               "id":3
            }
         ],
         "stock":[
            {
               "warehouse_id":1,
               "value":9
            }
         ],
         "handling_time":[
            {
               "warehouse_id":1,
               "value":0
            }
         ],
         "barcode":[

         ],
         "ean":[

         ],
         "commission":{
            "value":"20.0000",
            "type":"percentage",
            "id":"12492",
            "priority":"4",
            "created":"2010-01-16 11:25:02"
         },
         "validation_status":[
            {
               "value":9,
               "description":"Approved documentation",
               "errors":null
            }
         ],
         "offer_validation_status":{
            "value":1,
            "description":"Saleable",
            "errors":null
         },
         "ownership":1,
         "best_offer_sale_price":77.31,
         "best_offer_recommended_price":83.19,
         "number_of_offers":1
      }
   ]
}

这是转换的输出

part_number_key,buy_button_rank,category_id,id,brand,vendor_category_id,name,part_number,sale_price,currency,description,url,warranty,general_stock,weight,status,recommended_price,images,characteristics,attachments,vat_id,family,start_date,estimated_stock,reversible_vat_charging,min_sale_price,max_sale_price,offer_details,offer_properties,product_measurements,availability,stock,handling_time,barcode,ean,commission,validation_status,offer_validation_status,ownership,best_offer_sale_price,best_offer_recommended_price,number_of_offers
DASDSA,1,11,123,brand,,Name,"part number",12.31,RON,description,https://www.url.com,12,10,0,1,12.19,Array,Array,Array,1,Array,Array,10,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,11,11,1
D3129DKQW,1,456,123,Bluedio,,name,"part number",123,EUR,description,https://url.com,24,1,0,1,12,Array,Array,Array,1,Array,Array,144,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,77.31,83.19,1

如您所见,有数组而不是值,有人可以告诉我为什么吗?

我尝试过reset()函数,但仅从第一列(part_number_key)中获取值

foreach ($json as $line){  
   if (empty($firstLineKeys))   {  
      $firstLineKeys = array_keys($line); print_r("aici3"); fputcsv($f,
      $firstLineKeys); print_r("aici3"); $firstLineKeys = array_flip($firstLineKeys);
   }   fputcsv($f,
   array_merge($firstLineKeys,
   $line)); $first = reset($line); print_r($first);
}

我想提取所有列,但只显示每个列中每个列的第一行值,例如在“ images”列中,我只想提取第一个url,其余列都相同

还有一件事,忽略几列的最佳方法是什么?

谢谢!

0 个答案:

没有答案