当前位置: 移动技术网 > IT编程>开发语言>PHP > 根据ip调用新浪api获取城市名并转成拼音

根据ip调用新浪api获取城市名并转成拼音

2019年03月28日  | 移动技术网IT编程  | 我要评论

功能:

1,获取当前ip地址,
2,调用新浪api,获取到当前城市。
3,将中文转换为拼音后跳转。

复制代码 代码如下:

<?php
 include './pinyin.php';

//获取当前ip
function getip(){
  $onlineip='';
  if(getenv('http_client_ip')&&strcasecmp(getenv('http_client_ip'),'unknown')){
   $onlineip=getenv('http_client_ip');
  } elseif(getenv('http_x_forwarded_for')&&strcasecmp(getenv('http_x_forwarded_for'),'unknown')){
   $onlineip=getenv('http_x_forwarded_for');
  } elseif(getenv('remote_addr')&&strcasecmp(getenv('remote_addr'),'unknown')){
   $onlineip=getenv('remote_addr');
  } elseif(isset($_server['remote_addr'])&&$_server['remote_addr']&&strcasecmp($_server['remote_addr'],'unknown')){
   $onlineip=$_server['remote_addr'];
  }
  return $onlineip;
 }

 //获取城市信息api
 function getlocation($ip){
  $curl = curl_init();
  curl_setopt($curl, curlopt_url, "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip);
  curl_setopt($curl, curlopt_returntransfer, 1);
  curl_setopt($curl, curlopt_connecttimeout, 30);
  $str = curl_exec($curl);
  curl_close($curl);
  return $str;
 }

 //当前ip地址
 $currentip = getip();

 //通过当前ip获取信息
 $getlocation = getlocation($currentip);
 $currentinfo = json_decode($getlocation, true); 

 //判断ip是否为有效
 if($currentinfo['ret'] == '-1')
 {
  $currentinfo['city'] = 'unknown';
 }

 //当前城市中文名
 $currentcityname = $currentinfo['city'];  
 $currentcityename = $pin->pinyin("$currentcityname",'utf8');

 //城市拼音多音字
 switch($currentcityename)
 {
  case 'zhongqing':
   $currentcityename = 'chongqing';
  break;

  case 'shenfang':
   $currentcityename = 'shifang';
  break;

  case 'chengdou':
   $currentcityename = 'chengdu';
  break;

  case 'yueshan':
   $currentcityename = 'leshan';
  break;

  case 'junxian':
   $currentcityename = 'xunxian';
  break;

  case 'shamen':
   $currentcityename = 'xiamen';
  break;

  case 'zhangsha':
   $currentcityename = 'changsha';
  break;

  case 'weili':
   $currentcityename = 'yuli';
  break;

  case 'zhaoyang':
   $currentcityename = 'chaoyang';
  break;

  case 'danxian':
   $currentcityename = 'shanxian';
  break;

  default:
   $currentcityename = $pin->pinyin("$currentcityname",'utf8');
  break;
 }

 //重定向浏览器
 header("location: //www.jb51.net");
 exit;

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网