【问题标题】:Get specific values from CURL JSON从 CURL JSON 获取特定值
【发布时间】:2017-01-26 02:55:41
【问题描述】:

这是代码:

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$url = "http://extreme-ip-lookup.com/json/".$ip;

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
$info = curl_exec($curl);
curl_close($curl);

echo $info;
?>

我有这个输出:

{ "businessName" : "", "businessWebsite" : "", "city" : "Mountain View", "continent" : "North America", "country" : "United States", "countryCode" : "US", "ipName" : "google-public-dns-a.google.com", "ipType" : "Residential", "isp" : "Google", "lat" : "37.3860", "lon" : "-122.0838", "org" : "Google Inc.", "query" : "8.8.8.8", "region" : "California", "status" : "success" } 1

但我需要这个(仅城市或任何孤立值)

Mountain View

【问题讨论】:

  • $json = json_decode($info, true);回声 $json['city'];
  • 我尝试使用 json_decode,但我的结果是一样的。完整的信息,不仅仅是城市。也许是 json_decode 的服务器问题?有别的办法吗?没有json_decode?​​span>

标签: php arrays json curl


【解决方案1】:

你只需要解码 JSON,然后访问类属性:

$ipInfo = json_decode($info);
$city = $ipInfo->city;

【讨论】:

  • 我尝试使用 json_decode,但我的结果是一样的。完整的信息,不仅仅是城市。也许是 json_decode 的服务器问题?有别的办法吗?没有json_decode?​​span>
【解决方案2】:

json_decode

      $json = json_decode($info, true); 
      echo $json['city']; 

或者:

<?php
     $user_ip = getenv('REMOTE_ADDR');
     $geo = json_decode(file_get_contents("http://extreme-ip-lookup.com/json/$user_ip"));
     $country = $geo->country;
     $city = $geo->city;
     $ipType = $geo->ipType;
     $businessName = $geo->businessName;
     $businessWebsite = $geo->businessWebsite;

     echo "Location $city";
?>

【讨论】:

  • 我尝试使用 json_decode,但我的结果是一样的。完整的信息,不仅仅是城市。也许是 json_decode 的服务器问题?有别的办法吗?没有json_decode?​​span>
  • @ArtaxerxesSaint 的尝试
  • 他可能使用 curl 而不是 file_get_contents,并且他没有使用 CURLOPT_RETURNTRANSFER
【解决方案3】:

使用true 的参数检查json_decode 以获取数组。

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$url = "http://extreme-ip-lookup.com/json/".$ip;

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
$info = curl_exec($curl);
curl_close($curl);

$array = json_decode($info, true);
echo $array['city'];

【讨论】:

  • 我尝试使用 json_decode,但我的结果是一样的。完整的信息,不仅仅是城市。也许是 json_decode 的服务器问题?有别的办法吗?没有json_decode?​​span>
猜你喜欢
  • 1970-01-01
  • 2015-09-16
  • 2021-12-19
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2019-03-30
  • 2013-08-20
相关资源
最近更新 更多