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

PHP 手機歸屬地查詢:呼叫 WebXML WebService 實作

     編輯:PHP 綜合知識

完整程式碼

<?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_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => "mobileCode={$number}&userId=",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $xml = simplexml_load_string($response);
    if (strpos((string)$xml, 'https://') !== false) {
        echo '手機號碼格式錯誤!';
    } else {
        echo $xml; // 直接輸出 XML 文字節點內容
    }
}
?>

<form action="mobile.php" method="get">
手機號: <input type="text" name="number" />   <input type="submit" value="提交" />
</form>

改進建議

  1. 輸入驗證:if (!preg_match('/^1[3-9]\d{9}$/', $number)) 先檢查格式。
  2. 快取結果:相同號碼 24 小時內不重複查詢,存 Redis/Memcached/檔案。
  3. 錯誤處理:檢查 curl_errno()、HTTP 狀態碼、XML 解析失敗。
  4. HTTPS:API 支援 HTTPS 請改用,避免中間人竄改。
  5. 編碼:回傳 XML 可能為 GB2312,專案若為 UTF-8 需 mb_convert_encoding。

現代替代方案

方案優點缺點
本地資料庫(如 ipip.net、淘寶資料庫)零網路延遲、無限制、隱私安全需定期更新資料檔
Composer 套件:overtrue/phonenumber離線解析、支援國際號碼、格式化僅歸屬地/運營商,無實時狀態
付費 API:NumVerify、AbstractAPI即時、驗證有效性、風險評分成本、頻率限制
三大運營商官方 API權威、實時企業資質、審核嚴、費用高

資料庫離線查詢範例

// 使用 overtrue/phonenumber
require 'vendor/autoload.php';
use Overtrue\Phonenumber\Phonenumber;

$phone = new Phonenumber('13800138000');
echo $phone->getLocation(); // 北京 移動
echo $phone->getType();     // mobile
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved