利用PHP的curl函数获取IP地理位置API接口源码示例,调用的站长工具数据。
<?php
echo
'<html>
<head>
<title>IP地理位置接口</title></head></html>';
//以上内容输出页面标题
if
(!
empty
(
$_GET
[
"ip"
])){
//如果接口访问时带了IP参数,则查询参数中的地址
$local
=
$_GET
[
"ip"
];
}
else
{
$local
=
$_SERVER
[
"REMOTE_ADDR"
];
//否则查询自身本地IP地址
}
//下方代码为curl核心代码
$url
=
"https://ip.chinaz.com/"
.
$local
; //访问地址
$ch
= curl_init(
$url
);
curl_setopt(
$ch
, CURLOPT_HEADER, 1);
//使用自身协议头
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch
, CURLOPT_BINARYTRANSFER, true);
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYPEER, FALSE);
$response
= curl_exec(
$ch
);
//返回IP138的页面源码
$response
= preg_replace(
'/s+/'
,
''
,
$response
);
//删除源码中所有的空格
curl_close(
$ch
);
//curl核心代码结束,下面代码为取出中间文本
function
get_em(
$input
,
$start
,
$end
) {
$substr
=
substr
(
$input
,
strlen
(
$start
)+
strpos
(
$input
,
$start
),
(
strlen
(
$input
) -
strpos
(
$input
,
$end
))*(-1));
return
$substr
;
}
$string
=
$response
;
$start
=
'0lh45"><em>'
;
$end
=
'</em><aclass'
;
echo
'IP:'
.
$local
.
'<br>位置:'
.get_em(
$string
,
$start
,
$end
);
//输出查询IP和取出地理位置
?>