由于我也是刚学,所以有什么写的不对的不好的,让人看着不舒服的,我只想说:你来打我啊!
总所周知,我们程序员很多时候需要的数据和别人的网站上的一样,这里我们就要用到采集。
大哭的分割线
采集还是比较简单的,首相我们需要我们采集数据的网站地址,使用php函数:file_get_contents($url); $url 就是网站地址,它会读取目标网站的所有内容,
获取到内容之后,查看页面源代码,找到你需要的数据,然后使用正则表达式:// 或者## 还有函数:preg_metch和preg_metch_all; 匹配到数据,他会存到一个
数组中,然后我们通过处理数组得到数据存到数据库中。这里有自己采集的一个新闻网站中的标题、图片、和时间 是用CI框架做的;
class Welcome extends CI_Controller { public function index() { $url="http://news.ifeng.com/mainland/"; $str=file_get_contents($url); $str=iconv('utf-8','utf-8',$str); $txt='#<div class="juti_list">.*<a target="_blank" id="checkMore">#isU'; preg_match($txt,$str,$data); $txt2='#<a href=".*" target="_blank" title=".*" class="js_url js_title">(.*)</a>#isU'; $txt3='#<img src="(.*)" width="150" height="95">#isU'; $txt4='#<span>(.*)</span>#isU'; preg_match_all($txt2,$data[0],$data2); preg_match_all($txt3,$data[0],$data3); preg_match_all($txt4,$data[0],$data4); for($i=0;$i<count($data3[0]);$i++){ $arr[$i]['title']=$data2[1][$i]; $arr[$i]['img']=$data3[1][$i]; $arr[$i]['date']=$data4[1][$i]; } foreach($arr as $k=>$v){ $str2=file_get_contents($v['img']); $suffix=substr($v['img'],strrpos($v['img'],'.')); $url2="F:\wamp\www\month7\9.3\CodeIgniter-3.0.6\public\image/"; $img=time().rand().$suffix; file_put_contents($url2.$img,$str2); $arr[$k]['img']=$img; } foreach($arr as $v){ $this->db->insert('news2',$v); } $list=$this->db->get('news2')->result_array(); $this->load->vars('list',$list); $this->load->view('index.php'); }