本地数据库查询方案
若需批量查询多个手机号码的归属地,建议搭建独立的手机号码数据库。对于常规查询需求,无需购买昂贵的专业版数据库以节省成本。此处提供一个免费的ACCESS格式数据库,内含17万余条记录,涵盖常用的130-139、150-159及180-189等号段。用户可利用数据库工具将其转换为MYSQL或其他兼容版本。
最新手机号码数据库下载地址:http://xiazai.jb51.net/201209/yuanma/phone-number-database-jb51.rar
PHP+MYSQL手机号码归属地查询实现方法
基于前述步骤,我们已准备好MYSQL数据表。该表结构简洁,包含ID(序号)、code(区号)、num(手机号码段)、cardtype(手机卡类型)及city(归属地)。鉴于数据量庞大,应根据SQL查询逻辑建立合理的索引字段,从而显著提升查询性能。
获取归属地的核心在于判断手机号码段的归属区域。此功能主要通过特定函数实现,涉及GetAlabNum、cn_substr和str_replace等字符串处理函数,以及$dsql数据库操作类实例。
function GetTelphone($tel)
{
global $city,$dsql;
if(isset($tel)) $tel = GetAlabNum(trim($tel));//GetAlabNum函数用于替换全角数字,将可能存在的非法手机号码转换为数字;trim去除多余空格。
else return false;
if(strlen($tel) < 7) return false;
$tel = cn_substr($tel, 11);//先截取11个字符,防止是多个手机号码
//if(!is_numeric($tel)) return false;
if(cn_substr($tel, 1) == "0")//判断手机号码是否以0开头,这种情况可能会是座机号以0开头
{
if(cn_substr($tel, 2) == "01" || cn_substr($tel, 2) == "02") $tel = cn_substr($tel, 3);//3位区号
else $tel = cn_substr($tel, 4);
$row = $dsql->GetOne(" Select code,city as dd from `#@__tel` where code='$tel' group by code ");
}
else
{
$tel = cn_substr($tel, 7);
$row = $dsql->GetOne(" Select num,city as dd from `#@__tel` where num='$tel' ");
}
$city = $row['dd'];
if($city)
{
$city = str_replace("省", "-", $city);
$city = str_replace("市", "", $city);
$city = ""
[".$city."]";
return $city;
}
}
API接口调用方案
api实现方法,这里不需要自己的数据库但有限制了
主要使用curl实现,需要开启php对curl的支持。
<?php
header(“Content-Type:text/html;charset=utf-8″);
if (isset($_GET['number'])) {
$url = ‘http://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);
$data = simplexml_load_string($data);
if (strpos($data, ‘http://')) {
echo ‘手机号码格式错误!';
} else {
echo $data;
}
}
?> <form action="%E2%80%9Dmobile.php%E2%80%9D" method="”get”"> <br>手机号码: <input type="”text”" name="”number”"> <input type="”submit”" value="”提交”"> <br></form> 与php mysql手机号码归属地查询这个会慢很多,毕竟要通过第三方法数据。