Alexwall Alexwall - 2 months ago 15
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 freegeoip.net. 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:

<?php
$person = $_SERVER["REMOTE_ADDR"];

$url = "freegeoip.net/json/$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);

curl_close($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?

Answer

Add the following line after setting CURLOPT_HTTPHEADER:

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1); 

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.