用 php 提取 JSON

Extract JSON with php

正在尝试从 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.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php 中的非法字符串偏移量 'region' 行 191\nPHP 消息:PHP 警告: file_get_contents(h):无法打开流:/home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php 行 191\nPHP 消息中没有这样的文件或目录:PHP 警告:/home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php 行 191\nPHP 中的非法字符串偏移量 'region' 消息:PHP 警告:file_get_contents (h): 无法打开流:/home/url.com/app/public_html/wp-content/plugins/custom-ads-plugin/custom-ads.php 行 191\n'

中没有此类文件或目录

不,您不能在 "string url" 上执行 json_decode...您需要解码 url 的内容。然后做:

$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;