GTS Joe
GTS Joe

Reputation: 4142

Get JSON Data with PHP cURL

I have a simple script that outputs some JSON. I'm trying to retrieve the JSON contents in a variable with another PHP script, but when I do a var_dump(), I'm getting NULL instead of the JSON data.

Here's the JSON. The only output is: {"ProductID":"1000096","ProductStyleID":"1001029","ProductCategoryID":"1000004"}

json.php

$arr['ProductID'] = "1000096";
$arr['ProductStyleID'] = "1001029";
$arr['ProductCategoryID'] = "1000004";

$json_arr = json_encode($arr);
echo $json_arr;

And here's the cURL script, which right now is outputting NULL:

curl.php

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "/json.php");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);
var_dump(json_decode($result, true));

How can I retrieve the JSON echoed in the json.php script?

Upvotes: 2

Views: 587

Answers (2)

Oladimeji Ajeniya
Oladimeji Ajeniya

Reputation: 386

This is the URL to get the data:-

$url="https://.../api.php?action";

Using cURL:

//  Initiate curl
$cuh = curl_init();
// Disable SSL verification
curl_setopt($cuh, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($cuh, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($cuh, CURLOPT_URL,$url);
// Execute
$result=curl_exec($cuh);
// Closing
curl_close($cuh);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

If you see a basic CURL example:- http://php.net/manual/en/curl.examples-basic.php

You come to know that instead of:-

"/json.php"

You need to give full path like:-

(http://...) or (https://...) for your file (based on your server)

Note:- Rest of your code seems perfectly fine.Thanks

Upvotes: 3

Related Questions