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

发布时间:2019-09-30编辑:脚本学堂
本文介绍了根据ip调用新浪api获取城市名并转成拼音的php代码,大家做个参考。

实现如下功能:
1,获取当前IP地址
2,调用新浪api,获取到当前城市。
3,将中文转换为拼音后跳转。

相关链接:php IP获取城市API(纯真IP数据库)
 

复制代码 代码示例:

<?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: http://www.jb200.com");
 exit;