hemant thakur
hemant thakur

Reputation: 17

Retrieve Json Data Using CURL PHP

Using CURL here we retrieve data and print then save to file after that insert it into database.

$curl = curl_init();
$options=array(
    CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",
    CURLOPT_RETURNTRANSFER =>true,
    CURLOPT_ENCODING =>"",
    CURLOPT_FOLLOWLOCATION =>true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT=>30,
    CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
    CURLOPT_CUSTOMREQUEST => "GET", 
    CURLOPT_POSTFIELDS=>"", 
    CURLOPT_HTTPHEADER=> array(
        "authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
        "cache-control: no-cache"
    ),
    CURLOPT_HEADER=> true
);


curl_setopt_array($curl, $options);
$response = curl_exec($curl);

$err = curl_error($curl);
curl_close($curl);

if ($err){
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

The Result json is fine. now i want to save it in json file?

Upvotes: 2

Views: 48

Answers (1)

Hichem BOUSSETTA
Hichem BOUSSETTA

Reputation: 1857

to save a string to a file in php, you can use file_put_contents()

file_put_contents doc

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int

You can update your code as follows:

if ($err){
    echo "cURL Error #:" . $err;
} else {
    echo $response;

    //Write response to file
    file_put_contents("my_file.json", $response)
}

Upvotes: 1

Related Questions