0

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?

1
  • you can test/check response by hurl.it before try with your code Commented Sep 22, 2016 at 18:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.