我是抓取的问天网的内容,首先将城市id存入到数据库,当你输入城市名称的时候,首先查询数据库中城市名称对应的城市编号,问天网提供的城市和id地址为http://www.weather.com.cn/textFC/hz.shtml,然后根据问天的API地址http://m.weather.com.cn/data/城市编号.html可以获取一个json数据,过滤一下返回给用户
上代码
<?php
set_time_limit(0);//设置页面超时时间为永不过期
$url = 'http://www.weather.com.cn/textFC/hz.shtml';//获取城市id地址
$host = 'http://www.weather.com.cn/';//host地址
$files = @file_get_contents($url);//使用了php内置函数
$patten = '#<li><span><a href="http:\/\/www\.weather\.com\.cn\/weather\/([0-9]+)\.shtml">(.*)<\/a><\/span><\/li>#iUs';//将城市id通过这则提取出来,这里根据页面不同正则写法也不同
preg_match_all($patten,$files,$match);
print_r($match);
connect_sql();
//id入库
foreach($match[1] as $key=>$val){
$sql = "INSERT INTO city_id (city_name,city_bh) VALUES ('".$match[2][$key]."','".$val."')";
$rel = mysql_query($sql);
}
function connect_sql(){
$con = mysql_connect('localhost','root','123456') or die('mysql error :'.mysql_error());
mysql_select_db('test');
mysql_query('set names utf8');
}
?>
这个不是重点,所以写的比较简单,主要目的就是把城市名称和所对应的编号存入到数据库中
关注微信账号z510168343