Welcome to a tutorial on how to receive JSON data with PHP CURL. Are you expecting to receive some JSON data with a CURL call?
To receive JSON data with PHP CURL, simply use the json_decode()
function to turn the JSON string back into an object or array:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://site.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
curl_close($ch);
That covers the quick basics, but let us walk through a detailed example – Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
JSON DATA WITH PHP CURL
All right, let us now get into an example of receiving and decoding JSON data with PHP CURL.
DUMMY JSON DATA
<?php
$data = [
"name" => "Jon Doe",
"email" => "jon@doe.com",
"colors" => ["Red", "Green", "Blue"]
];
echo json_encode($data);
Nothing to see here. Just a dummy script for testing, to output a dummy JSON encoded string.
CURL RECEIVE JSON DATA
<?php
// (A) CURL FETCH
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/1-dummy.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
// (B) RESULTS
// (B1) ERROR
if (curl_errno($ch)) { echo curl_error($ch); }
// (B2) JSON DECODE
else {
echo $result; // string
$decoded = json_decode($result);
print_r($decoded); // standard object
$decoded = json_decode($result, true);
print_r($decoded); // array
}
// (B3) CURL CLOSE
curl_close($ch);
This is pretty much the same as the snippet in the introduction, but take extra note of $result
:
- In the “raw” form, direct from the server – It is a JSON-encoded string.
- After we do a
json_decode($result)
, it will be parsed into an object. Yes, this is a common pitfall among beginners – Not an array, but an object. - If you want to parse the results into an array, do
json_decode($result, true)
instead.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- JSON Encode – PHP
- JSON Decode – PHP
- CURL – PHP
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!