如何使用标题创建CSV文件,以便将其导入Excel

时间:2019-07-09 11:52:30

标签: php arrays csv export

我正在尝试使用此api并导出JSON结果,以便可以将其导入Excel。

我已经尝试过下面的代码,但是标题是垂直存储的,而不是存储在文件的顶部,然后在下面打印值。该文件中有多个关键字,因此它不仅仅是查询一个关键字。


$apikey = 'XXXXXXXXXXXX';

$array = explode("\n", file_get_contents('kw1.txt'));

$params = [
  'apikey' => $apikey,
  'keyword' => $array,
  'metrics_location' => '2840',
  'metrics_language' => 'en',
  'metrics_network' => 'googlesearchnetwork',
  'metrics_currency' => 'USD',
  'output' => 'json',
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.keywordtool.io/v2/search/volume/google');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($ch);
$response = json_decode($output, TRUE);

//Decode the JSON and convert it into an associative array.
$jsonDecoded = $response;

//Give our CSV file a name.
$csvFileName = 'example.csv';

$fileContent=[];

foreach ($response as  $key =>$value1){
    foreach ($value1 as $key2 => $value2){
           foreach ($value2 as $key3 => $value3){
                $fileContent[]=[$key2, $key3, $value3];
           }
    }
}


$fp = fopen('file.csv', 'w');

foreach ($fileContent as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

结果是

cat,string,cat
cat,volume,6120000
cat,m1,7480000
cat,m1_month,5
cat,m1_year,2019
cat,m2,6120000
cat,m2_month,4
cat,m2_year,2019
cat,m3,6120000
cat,m3_month,3
cat,m3_year,2019
cat,m4,6120000
cat,m4_month,2
cat,m4_year,2019
cat,m5,6120000
cat,m5_month,1
cat,m5_year,2019
cat,m6,6120000
cat,m6_month,12
cat,m6_year,2018
cat,m7,6120000
cat,m7_month,11
cat,m7_year,2018
cat,m8,6120000
cat,m8_month,10
cat,m8_year,2018
cat,m9,6120000
cat,m9_month,9
cat,m9_year,2018
cat,m10,6120000
cat,m10_month,8
cat,m10_year,2018
cat,m11,6120000
cat,m11_month,7
cat,m11_year,2018
cat,m12,6120000
cat,m12_month,6
cat,m12_year,2018
cat,cpc,0.270114
cat,cmp,0.029219098
dog,string,dog
dog,volume,7480000
dog,m1,7480000
dog,m1_month,5
dog,m1_year,2019
dog,m2,7480000
dog,m2_month,4
dog,m2_year,2019
dog,m3,7480000
dog,m3_month,3
dog,m3_year,2019

我希望看到的是:

keyword,volume,m1,m1_month,m1_year...
cat,6120000,7480000,5,2019...
dog,......

1 个答案:

答案 0 :(得分:0)

替换

$fileContent=[]; 

使用

$fileContent[] = ['keyword','m1_month','m1_year'];