PHP号码归属地区分自动化查询API封装
爬虫拿到的数据全部存放到数据库,这里封装的只从数据库读取和区分数据到新的数据库:
<?php /* 电话号码区分地址.储存到数据库; 单例模式; the author kexin; date 2018/5/10; */ set_time_limit(0); class Filter{ private $_phone = ''; private $_api = 'http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel='; private $_user; private $_host; private $_pwd; private $_dbname; private static $conn = null; private function __construct () { } public static function _interance () { // 返回实例 if (self::$conn == null) return self::$conn = new Filter; } /* param host param user param pwd param dbname return null */ public function _conn ($host, $user, $pwd, $dbname) { $this->_host = $host; $this->_user = $user; $this->_pwd = $pwd; $this->_dbname = $dbname; } public function _select ($where) { try { $pdo = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_user, $this->_pwd); $pdo->query("SET CHARSET 'utf8'"); } catch (PDOException $e) { die("Connection fail:") . $e->getMessage(); } $sql = "SELECT * FROM phone where id = " . $where; $stmt = $pdo->prepare($sql); $stmt->execute(); while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) { if ($result != []) return $result; } } /* param phone 电话 return null */ public function _setdata ($phone) { if ($phone != null and strlen($phone) == 11) { $this->_phone = $phone; } } /* param phone 电话 param api api地址 return json 字符串 */ public function _rseponseText () { $ch = curl_init(); $str = $this->_api . $this->_phone; curl_setopt($ch, CURLOPT_URL, $str); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); return (array) json_decode($output,true); } public function _savedata ($number, $city) { $val = null; $arr = [$number, $city]; if (in_array($val, $arr)) return false; try { $pdo = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_user, $this->_pwd); $pdo->query("SET CHARSET 'utf8'"); } catch (PDOException $e) { die ("Connection fail:") . $e->getMessage(); } $sql = "insert into attribution (number, city) values ('{$number}', '{$city}')"; $result = $pdo->exec($sql); if ($result) { return "Insert success..."; } else { return "Insert fail..."; } } }
在请求API的时候其实可以先查询本地数据库是否有前7位是否一样(有待验证)
查询mysql数据库始终比http请求快太多,可以的话在查询mysql数据库之前使用redis来就更好了~
浙公网安备 33010602011771号