I'm trying to use this api and export the JSON result so that it can be imported into Excel.
I've tried the code below but the headers are being stored vertically rather than being at the top of the file then printing the values underneath. There are multiple keywords in the file so it's not just querying one.
$apikey = 'XXXXXXXXXXXX';
$array = explode("
", 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);
The results are
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
What I'm hoping to see is:
keyword,volume,m1,m1_month,m1_year...
cat,6120000,7480000,5,2019...
dog,......