Reputation: 17
Trying to get IP geolocation from whoisxmlapi to work. When I'm using the sample code they provide, everything is working fine. Here is the code I use.
<?php
$ip = $_SERVER["HTTP_X_REAL_IP"];
$api_key = 'your_api_key';
$api_url = 'https://geoipify.whoisxmlapi.com/api/v1';
$url = "{$api_url}?apiKey={$api_key}&ipAddress={$ip}";
print(file_get_contents($url));
?>
Here is the output I get printed on my page.
{"ip":"174.222.131.171","location":{"country":"US","region":"California","city":"Fresno","lat":36.74773,"lng":-119.77237,"postalCode":"93650","timezone":"-07:00"}}
Then, when I try to echo region only with following code, there is absolutely nothing on the page
$url = "{$api_url}?apiKey={$api_key}&ipAddress={$ip}";
$ipfeed = json_decode($url);
echo $ipfeed->region;
UPDATE: error log record
[Mon Sep 17 18:20:01.101218 2018] [proxy_fcgi:error] [pid 6803] [client 127.0.0.1:34987] AH01071: Got error 'PHP message: PHP Warning: Illegal string offset 'region' in /home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php on line 191\nPHP message: PHP Warning: file_get_contents(h): failed to open stream: No such file or directory in /home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php on line 191\nPHP message: PHP Warning: Illegal string offset 'region' in /home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php on line 191\nPHP message: PHP Warning: file_get_contents(h): failed to open stream: No such file or directory in /home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php on line 191\n'
Upvotes: 0
Views: 191
Reputation: 2424
No, you cannot do json_decode
on a "string url"... you need to decode the contents of the url. Then do:
$ip = $_SERVER["HTTP_X_REAL_IP"];
$api_key = 'your_api_key';
$api_url = 'https://geoipify.whoisxmlapi.com/api/v1';
$url = "{$api_url}?apiKey={$api_key}&ipAddress={$ip}";
$json = file_get_contents($url);
$ipfeed = json_decode($json);
echo $ipfeed->location->region;
Upvotes: 5