萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 解析新浪/淘寶 IP 地址 API 回傳 JSON:Unicode 轉 UTF-8 與陣列存取完整範例

呼叫新浪或淘寶 IP 定位 API 回傳 JSON,中文欄位以 \uXXXX Unicode 轉義編碼。PHP 需正確解碼並轉為關聯陣列,才能直接存取 $data['country'] 等欄位。本文示範完整流程與正則替換技巧。

API 回傳範例 (淘寶)

{
  "code": 0,
  "data": {
    "country": "\u4e2d\u56fd",
    "country_id": "CN",
    "area": "\u534e\u5317",
    "area_id": "100000",
    "region": "\u5317\u4eac\u5e02",
    "region_id": "110000",
    "city": "\u5317\u4eac\u5e02",
    "city_id": "110100",
    "county": "",
    "county_id": "-1",
    "isp": "\u8054\u901a",
    "isp_id": "100026",
    "ip": "123.123.123.123"
  }
}

核心解碼步驟

<?php
$ip = '123.123.123.123';
$url = "https://ip.taobao.com/service/getIpInfo.php?ip={$ip}";

// 1. 取得原始 JSON 字串
$json = @file_get_contents($url);
if ($json === false) {
    die('API 請求失敗');
}

// 2. 關鍵:將 \uXXXX 轉為真正 UTF-8 字元
// PHP 5.4+ json_decode 可直接處理 \uXXXX,但舊版需手動轉碼
// 通用做法:preg_replace_callback (PHP 5.3+)
$json = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($m) {
    return mb_convert_encoding(pack('H*', $m[1]), 'UTF-8', 'UCS-2BE');
}, $json);

// 3. 解碼為關聯陣列
$data = json_decode($json, true);  // true = 關聯陣列
if (json_last_error() !== JSON_ERROR_NONE) {
    die('JSON 解析錯誤:' . json_last_error_msg());
}

// 4. 存取欄位
if ($data['code'] == 0 && isset($data['data'])) {
    $loc = $data['data'];
    echo "國家:{$loc['country']} ({$loc['country_id']})
"; echo "地區:{$loc['area']} ({$loc['area_id']})
"; echo "省份:{$loc['region']} ({$loc['region_id']})
"; echo "城市:{$loc['city']} ({$loc['city_id']})
"; echo "ISP:{$loc['isp']} ({$loc['isp_id']})
"; echo "IP:{$loc['ip']}
"; } else { echo "查詢失敗,代碼:{$data['code']}"; } ?>

舊版 PHP (5.3-) 相容寫法


// 使用 create_function (已棄用但仍可用) 或預先定義函數
function unicode_decode($matches) {
    return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UCS-2BE');
}
$json = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'unicode_decode', $json);

進階:封裝為可重用函數

function getIpLocation($ip, $provider = 'taobao') {
    $urls = [
        'taobao' => "https://ip.taobao.com/service/getIpInfo.php?ip={$ip}",
        'sina'   => "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={$ip}",
    ];
    $url = $urls[$provider] ?? $urls['taobao'];
    
    $json = @file_get_contents($url);
    if (!$json) return ['error' => 'request_failed'];
    
    // 統一處理 Unicode 轉義
    $json = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($m) {
        return mb_convert_encoding(pack('H*', $m[1]), 'UTF-8', 'UCS-2BE');
    }, $json);
    
    $data = json_decode($json, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['error' => 'json_decode_failed', 'msg' => json_last_error_msg()];
    }
    
    // 統一輸出格式
    if ($provider === 'taobao') {
        return $data['code'] == 0 ? ['success' => true, 'data' => $data['data']] : ['error' => 'api_error', 'code' => $data['code']];
    } else {
        // 新浪格式較平坦
        return isset($data['country']) ? ['success' => true, 'data' => $data] : ['error' => 'api_error'];
    }
}

// 使用
$result = getIpLocation('123.123.123.123');
if ($result['success']) {
    print_r($result['data']);
}

效能與快取建議

  • 同一 IP 短時間內重複查詢無意義,建議用 Redis/Memcached 快取 24 小時:ip:location:{ip}
  • 大量查詢時改用 curl_multi 併發請求,或離線下載 IP 庫 (如 ip2region、GeoIP2) 本地查詢
  • API 有頻率限制,生產環境請申請商業授權或自建 IP 庫

小結

PHP 處理淘寶/新浪 IP API 回傳 JSON 關鍵在於:preg_replace_callback 將 \uXXXX 轉為 UTF-8 字元,再 json_decode($json, true) 取得關聯陣列。封裝為統一介面函數並加入快取,即可高效支援業務需求。

copyright © 萬盛學電腦網 all rights reserved