首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 調用新浪 IP API 獲取城市並轉拼音:完整可用代碼

     編輯:PHP 相關知識

功能流程

  1. 獲取客戶端真實 IP(支援代理頭)。
  2. 請求新浪 IP 查詢接口(JSON 格式)。
  3. 解析城市中文名。
  4. 轉換為拼音(處理多音字特例)。
  5. 重定向到對應城市站點。

核心代碼

<?php
require_once 'Pinyin.php'; // 需自行引入拼音類(如 overtrue/pinyin)

// 1. 獲取 IP
function getClientIP(): string {
    foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) {
            $ips = array_map('trim', explode(',', $_SERVER[$key]));
            foreach ($ips as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
    }
    return '127.0.0.1';
}

// 2. 調用新浪 API
function getLocationBySina(string $ip): ?array {
    $url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={$ip}";
    $ctx = stream_context_create(['http' => ['timeout' => 5]]);
    $json = @file_get_contents($url, false, $ctx);
    return $json ? json_decode($json, true) : null;
}

// 3. 拼音轉換(使用 overtrue/pinyin)
$pinyin = new Overtrue\Pinyin\Pinyin();

$ip = getClientIP();
$loc = getLocationBySina($ip);

$city = $loc['city'] ?? '未知';
if ($loc['ret'] ?? 0 == -1) $city = '未知';

// 4. 多音字修正映射表
$polyphoneMap = [
    '重慶' => 'chongqing', '石坊' => 'shifang', '成都' => 'chengdu',
    '樂山' => 'leshan', '濬縣' => 'xunxian', '廈門' => 'xiamen',
    '長沙' => 'changsha', '玉里' => 'yuli', '朝陽' => 'chaoyang',
    '單縣' => 'shanxian',
];

$cityPinyin = $polyphoneMap[$city] ?? strtolower($pinyin->permalink($city)); // permalink 輸出小寫無分隔

// 5. 重定向
$targetUrl = "https://{$cityPinyin}.example.com"; // 替換為實際域名規則
header("Location: {$targetUrl}");
exit;

依賴安裝建議

composer require overtrue/pinyin

Pinyin::permalink() 直接生成適合 URL 的小寫拼音,無需手動 strtolower。

生產環境優化

  • 緩存 IP→城市映射:Redis 存儲,TTL 30 天,減少外部 API 請求。
  • 異步非阻塞:使用 Swoole/Workerman 或消息隊列處理,避免阻塞用戶請求。
  • 備選 API:新浪接口不穩定,建議接入高德/騰訊/百度付費 IP 定位 API 作為主查詢,新浪作為降級。
  • HTTPS:新浪接口僅支援 HTTP,生產環境會觸發混合內容警告,建議服務端代理轉發至 HTTPS。

完整 Composer 專案結構

project/
├── composer.json
├── src/
│   └── CityRedirector.php
└── public/
    └── index.php  // 入口文件,僅調用 CityRedirector::run()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved