2017-01-26 113 views
0

这是代码:获取特定值

<?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 
+0

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

+0

我尝试使用json_decode,但我的结果是一样的。充分的信息,不只是城市。也许与json_decode服务器问题? 有没有别的办法?没有json_decode? –

回答

0

用参数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']; 
+0

我尝试使用json_decode,但我的结果是一样的。充分的信息,不只是城市。也许与json_decode服务器问题? 有没有别的办法?没有json_decode? –

1

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

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

我尝试使用json_decode,但我的结果是一样的。充分的信息,不只是城市。也许与json_decode服务器问题? 有没有别的办法?没有json_decode? –

1

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"; 
?> 
+0

我尝试使用json_decode,但我的结果是一样的。充分的信息,不只是城市。也许与json_decode服务器问题? 有没有别的办法?没有json_decode? –

+0

@ ArtaxerxesSaint's try – mwweb

+0

他可能使用curl而不是file_get_contents,并且他没有使用CURLOPT_RETURNTRANSFER – hanshenrik