通過調用 WebXML 提供的免費手機歸屬地查詢 WebService,實現一個簡單的手機號碼歸屬地查詢接口。支持 GET 請求傳遞手機號,返回歸屬地信息或錯誤提示。
<?php
header("Content-Type: text/html; charset=utf-8");
if (isset($_GET['number'])) {
$url = 'https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo';
$number = $_GET['number'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "mobileCode={$number}&userId=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data);
// 返回結果中若包含 https:// 則表示格式錯誤
if (strpos($xml, 'https://') !== false) {
echo '手機號碼格式錯誤!';
} else {
echo $xml;
}
}
?>
<form action="mobile.php" method="get">
手機號碼: <input type="text" name="number" />
<input type="submit" value="提交" />
</form>
mobileCode 參數。simplexml_load_string() 解析返回的 XML 字符串。https:// 的字符串,據此判斷。/^1[3-9]\d{9}$/),減少無效請求。// 瀏覽器訪問
https://yourdomain.com/mobile.php?number=13800138000
// 返回示例(XML 文本)
手機號碼: 13800138000
歸屬地: 廣東 廣州 移動