[英]Get a JSON response for the API request
我正在嘗試為API請求獲取json響應。
$GEOCODE = "http://api.ipinfodb.com/v3/ip-city/?key=$API_KEY&ip=70.27.250.191";
$json = file_get_contents($GEOCODE);
$data = json_decode($json);
dd($data);
返回輸出: null
。 但是,當我直接在地址欄中嘗試使用它時,它就可以工作了。 我做錯了嗎? 請幫我。
您需要請求json:
$GEOCODE = "http://api.ipinfodb.com/v3/ip-city/?key=$API_KEY&ip=70.27.250.191&format=json"; //<--THIS
$json = file_get_contents($GEOCODE);
$data = json_decode($json);
dd($data);
//output:
object(stdClass)#7 (11) {
["statusCode"]=>
string(2) "OK"
["statusMessage"]=>
string(0) ""
["ipAddress"]=>
string(13) "70.27.250.191"
["countryCode"]=>
string(2) "CA"
["countryName"]=>
string(6) "Canada"
["regionName"]=>
string(6) "Quebec"
["cityName"]=>
string(8) "Montreal"
["zipCode"]=>
string(7) "H1A 0A1"
["latitude"]=>
string(7) "45.5088"
["longitude"]=>
string(8) "-73.5878"
["timeZone"]=>
string(6) "-05:00"
}
您尚未提供要用於接收響應的有效格式。根據IP Info DB的官方文檔 ,API返回原始響應。 為了獲得JSON響應,請在API請求中包含參數format
。 因此,您的API URL現在變為:
$GEOCODE = "http://api.ipinfodb.com/v3/ip-city/?key=$API_KEY&format=json&ip=70.27.250.191";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.