2017-01-26 118 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