用php提取JSON

问题描述 投票:0回答:1

试图从whoisxmlapi工作获得IP地理位置。当我使用他们提供的示例代码时,一切正常。这是我使用的代码。

<?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));
?>

这是我在页面上打印的输出。

{"ip":"174.222.131.171","location":{"country":"US","region":"California","city":"Fresno","lat":36.74773,"lng":-119.77237,"postalCode":"93650","timezone":"-07:00"}} 

然后,当我尝试仅使用以下代码回显区域时,页面上绝对没有任何内容

$url = "{$api_url}?apiKey={$api_key}&ipAddress={$ip}";
$ipfeed = json_decode($url);
echo $ipfeed->region;

更新:错误日志记录

[Mon Sep 17 18:20:01.101218 2018] [proxy_fcgi:error] [pid 6803] [client 127.0.0.1:34987] AH01071:收到错误'PHP消息:PHP警告:/ home / url中的非法字符串偏移'region'第191行上的.com / app / public_html / wp-content / plugins / custom-ads-plugin / custom-ads.php消息:PHP警告:file_get_contents(h):无法打开流:没有这样的文件或目录/home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php第191行\ n \ nPHP消息:PHP警告:/ home / url中的非法字符串偏移'region'。第191行上的com / app / public_html / wp-content / plugins / custom-ads-plugin / custom-ads.php消息:PHP警告:file_get_contents(h):无法打开流:/中没有此类文件或目录第191行上的home / url.com / app / public_html / wp-content / plugins / custom-ads-plugin / custom-ads.php \ n'

php json api geoip
1个回答
5
投票

不,你不能在“字符串网址”上做json_decode ...你需要解码网址的内容。然后做:

$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;
© www.soinside.com 2019 - 2024. All rights reserved.