利用淘宝提供的json数据,把查到的信息存入到本地数据库中,下次查询时直接从本地数据库中读取。
1.效率快。
2.以防有一天不再提供这个接口了,不至于此功能完全不能用
淘宝提供的数据网址:http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=
1)检验给出的手机号是否合法
/*校验手机号码合法
* @param $phone
* @return bool
*/
public static function verifyPhone($phone=NULL){
$ret = false;
if ($phone){
if (preg_match('/^1[34578]{1}\d{9}/', $phone)){
$ret = true;
}
}
return $ret;
}
2)确定完整网址,并返回数据
使用file_get_contents($url)接受数据时首先在.ini文件中开启php_openssl.dll功能
/*
* 将网址与手机号参数链接
* return 字符串数据
*/
class HttpRequest{
public static function request($url,$params){
$response = null;
if ($url){
if (is_array($params) and count($params)){
if (strrpos($url, '?')){
$url = $url.'&'.http_build_query($params);
}else {
$url = $url.'?'.http_build_query($params);
}
$client=file_get_contents($url);
}
}
return $client;
}
}
3)格式化数据,并且转换为utf-8编码.。返回一维数组
/*
* 格式化数据
*/
public static function formatData($data = NULL){
$ret = false;
if ($data){
preg_match_all("/(\w+):'([^']+)/", $data,$res);
$items = array_combine($res[1], $res[2]);
foreach ($items as $key=>$val){
$ret[$key] = iconv('GBK', 'UTF-8', $val);
}
}
return $ret;
}
4)将一维数组转换为json字符串存入数据库中。json_encode($date);
数组转换为json字符串时汉字会变成unicod字符编码的一串字符串,
所以在存入数据库之前先把汉字的字符串转换为汉字再存入数据库中。
用到了正则表达式:
//讲汉字转变的字符串转变成汉字
$json=preg_replace("#\\\u([0-9a-f]{4}+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $json);