Alexwall Alexwall - 1 month ago 9x
JSON Question

PHP JSON parsing with cURL

I want to create a simple page that prints the region you are in, I am using an API from this site I have it set up so it runs a users ip through the site and returns JSON, however I am having issues parsing that response. This is the code I have written:

$person = $_SERVER["REMOTE_ADDR"];

$url = "$person";

$cURL = curl_init();

curl_setopt($cURL, CURLOPT_URL, $url);

curl_setopt($cURL, CURLOPT_HTTPGET, true);

curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'

$result = curl_exec($cURL);


$json = json_decode($result, true);

echo $json['region_name'];
echo $json['city'];

However for some reason, it still prints the full response from the server API... how do I fix this?


Add the following line after setting CURLOPT_HTTPHEADER:


By default curl_exec() outputs the response out directly and it returns TRUE on success or FALSE on failure. If you set CURLOPT_RETURNTRANSFER to TRUE, curl_exec() will return the actual result of successful operation, but still will return FALSE on failure.