本篇文章为大家展示了利用PHP怎么对地理位置进行获取,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
获取IP使用的是经典的逻辑,地理定位使用的是SINA的通用接口。
使用方法详见源码:
复制代码 代码如下:
<?php
/*
* GET LOCATION BY SINA IP INTERFACE
*
* @SOULTEARY 2013.04.14
*/
classIP
{
private $args=array();
function__construct()
{
$this->args=self::init_args(func_get_args());
$ip=self::GetIP();
$ret=preg_match_all('/(\d+\.){3}\d+/i',$ip,$result);
if(!$ret){
returnfalse;
}else{
$result=$result[0];
}
if(isset($this->args['ONLYIP'])&&$this->args['ONLYIP']==true){
if(isset($this->args['FORMAT'])&&$this->args['FORMAT']=='JSON'){
$result=json_encode($result);
}else{
$result=implode(',',$result);
}
if(isset($this->args['ECHO'])&&$this->args['ECHO']==true){
echo$result;
returntrue;
}else{
return$result;
}
}else{
$apiURL='http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip='.$result[0];
if(isset($this->args['FORMAT'])&&$this->args['FORMAT']=='JSON'){
$apiURL.='&format=json';
$return=$this->ipCURL($apiURL);
}else{
$return=$this->ipCURL($apiURL);
$return=iconv("GBK//IGNORE","UTF-8",$return);
}
if(isset($this->args['ECHO'])&&$this->args['ECHO']==true){
echo$return;
returntrue;
}else{
return$return;
}
}
}
public functioninit_args($args)
{
$result=array();
for($i=0,$n=count($args);$i<$n;$i++){
$result=self::associative_push($args[$i],$result);
}
return$result;
}
public functionassociative_push($arr,$tmp)
{
if(is_array($tmp)){
foreach($tmpas$key=>$value){
$arr[$key]=$value;
}
return$arr;
}
returnfalse;
}
public functionGetIP()
{
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])&&$_SERVER['HTTP_X_FORWARDED_FOR']&&strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'],'unknown')){
return$_SERVER['HTTP_X_FORWARDED_FOR'];
}elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')){
return$_SERVER['REMOTE_ADDR'];
}
}
private functionipCURL($url)
{
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
ob_start();
curl_exec($ch);
curl_close($ch);
$result=ob_get_contents();
ob_end_clean();
return$result;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>demo</title>
<script type="text/javascript">
varip="<?php new IP(array('ONLYIP'=>true, 'ECHO'=>true));?>";
vardata=<?php newIP(array('FORMAT'=>'JSON','ECHO'=>true));?>;
varresult='';
for(oo indata){
result+=oo+':'+data[oo]+"\n";
}
alert(result+ip);
</script>
</head>
<body>
<h2>CODE:</h2>
<h3>GETIP</h3>
<p>'ONLYIP'=>true,'ECHO'=>true</p>
<p><?phpnewIP(array('ONLYIP'=>true,'ECHO'=>true));?></p>
<P>'ONLYIP'=>true,'FORMAT'=>'JSON','ECHO'=>true</P>
<p><?phpnewIP(array('ONLYIP'=>true,'FORMAT'=>'JSON','ECHO'=>true));?></p>
<h3>GET Location</h3>
<p>'ECHO'=>true</p>
<p><?phpnewIP(array('ECHO'=>true));?></p>
<p>'FORMAT'=>'JSON','ECHO'=>true</p>
<p><?php newIP(array('FORMAT'=>'JSON','ECHO'=>true));?></p>
</body>
</html>
上述内容就是利用PHP怎么对地理位置进行获取,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。