呼叫新浪或淘寶 IP 定位 API 回傳 JSON,中文欄位以 \uXXXX Unicode 轉義編碼。PHP 需正確解碼並轉為關聯陣列,才能直接存取 $data['country'] 等欄位。本文示範完整流程與正則替換技巧。
{
"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']}";
}
?>
// 使用 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:location:{ip}curl_multi 併發請求,或離線下載 IP 庫 (如 ip2region、GeoIP2) 本地查詢PHP 處理淘寶/新浪 IP API 回傳 JSON 關鍵在於:preg_replace_callback 將 \uXXXX 轉為 UTF-8 字元,再 json_decode($json, true) 取得關聯陣列。封裝為統一介面函數並加入快取,即可高效支援業務需求。