这里用的file_put_contents,你也可以用别的,直接怼代码:
//拼接传递的参数 $getData = array( 'query' => '127.0.0.1', 'resource_id' => '6006', 'oe' => 'UTF-8', 'format' => 'json' ); $getData = http_build_query($getData); $opts = array( 'http'=>array( 'method'=>"POST", 'header'=>"Content-type:application/x-www-form-urlencoded " . "Content-length:". strlen($getData) ." ", "content"=>$getData, ) ); //获取Ip所属位置 $context = stream_context_create($opts); $fp = file_get_contents('http://opendata.baidu.com/api.php', false, $context); var_dump(json_decode($fp, true));
返回的数据样式为:
array (4) { ["status"]=> string(1) "0" ["t"]=> string(0) "" ["set_cache_time"]=> string(0) "" ["data"]=> array(1) { [0]=> array (15) { ["location"]=> string(31) "北京市北京市 不告诉你" ["titlecont"]=> string(14) "IP地址查询" ["origip"]=> string(14) "123.206.79.176" ["origipquery"]=> string(14) "123.206.79.176" ["showlamp"]=> string(1) "1" ["showLikeShare"]=> int(1) ["shareImage"]=> int(1) ["ExtendedLocation"]=> string(0) "" ["OriginQuery"]=> string(14) "123.206.79.176" ["tplt"]=> string(2) "ip" ["resourceid"]=> string(4) "6006" ["fetchkey"]=> string(14) "123.206.79.176" ["appinfo"]=> string(0) "" ["role_id"]=> int(0) ["disp_type"]=> int(0) } } }