1

I have written this code to get data from API URL. All data is written to my file, but I can't find solution to make it look like Json format in file, what I am missing? Everything I tried in file showing like text (Added example below) and what I want. Maybe someone will help me with this :). Thanks!

Source code using php curl to get and save data

<?php
$token = "eyJ";
$ch = curl_init("https://api.xxx.com/api/Catelo/Prod?cat=MPHEFGZ");
$fp = fopen("prod.json", "w");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Authorization: Bearer ' . $token
   ));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

I want it to save to file like this:

What I expect (saved format):

"FIFA_Last_World_Cup_final":
{
    "Year": "2018",
    "data":
    {
        "Winner": "France",
        "Score": "4-2",
        "Runner-up": "Croatia"
    }
}

What I get now when data is saved to file:

[{"id":1,"Code":1,"name":"TV","manu":"32","v":"P","v":"P","c":"T","q":"0","p":1.0,"d":1.0,"imagePath":"e0bc7.Jpeg","thumbnailImagePath":"0bc7.Jpeg","fullDsc":"32\"","cury":"E","httpD":"548","packy":1,"ty":"24","eae":"","obligaKit":0,"reerty":0,"proate":0,"pront":70,"quane2":"0","pri":0.0,"lotN":"","p":0.0,"i":70}
zte813
  • 95
  • 1
  • 10
  • @NigelRen Yes, what I want is to save data as json format, not raw. Just I don't find out how to make it pretty.. – zte813 Nov 13 '19 at 16:14
  • Possible duplicate of [Pretty-Printing JSON with PHP](https://stackoverflow.com/questions/6054033/pretty-printing-json-with-php) – grooveplex Nov 13 '19 at 17:03

1 Answers1

3

As you are not processing the response from the API, what you see is just how the response is sent. To format it, you can capture the output (using CURLOPT_RETURNTRANSFER) and then decode the response - re-encoding it with JSON_PRETTY_PRINT.

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $token
));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the JSON from the API
$response = curl_exec($ch);
curl_close($ch);
fclose($fp);

// Decode it, re-encode with formatting
echo json_encode(json_decode($response), JSON_PRETTY_PRINT);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55