<?php
/**
* 采集soho网页新闻
*/
// header头
header("content-type:text/html;charset=utf8");
// 网站地址
$url="http://sports.sohu.com/nba.shtml";
// 获取网站内容
$str=file_get_contents($url);
// 转码
$str=iconv('GBK','utf-8',$str);
// pdo连接数据库
$pdo=new PDO("mysql:host=localhost;dbname=caiji" ,"root","root");
$pdo->exec("set names utf8");
// 获取网页内容`
$reg='#<div style="display: block; height: 110px; overflow: hidden;" class="l">.*<div class="blank10"></div>#isU';
preg_match($reg, $str,$arr);
// 分步正则获取图片、标题、详情
$reg2='#<img alt="NBA" src="(.*)" border="0" height="100" width="100"></a></div>#isU';
$reg3='#<h4><a onFocus="undefined" title="" href=".*" target="_blank">(.*)</a></h4>#isU';
$reg4='#<p>(.*)<a onFocus="undefined" href=".*" target="_blank">.*<div class="r"></div></div>#isU';
// var_dump($arr);
preg_match_all($reg2,$arr[0],$image);
preg_match_all($reg3,$arr[0],$title);
preg_match_all($reg4,$arr[0],$content);
// 添加到同一个数组
$data=array();
// 将图片保存到本地
foreach ($image[1] as $key => $value) {
// 截取后缀
$exm=substr($value,strrpos($value,'.'));
// 拼写路径
$image_name='./image/'.time().rand(1000,9999).$exm;
// var_dump($image_name);
// 获取图片内容
$value=file_get_contents($value);
file_put_contents($image_name,$value);
$data[$key]['image']=$image_name;
}
// foreach ($image[1] as $key => $value) {
// $data[$key]['image']=$value;
// }
foreach ($title[1] as $key => $value) {
$data[$key]['title']=$value;
}
foreach ($content[1] as $key => $value) {
$data[$key]['content']=$value;
}
// 循环入库
foreach ($data as $key => $value) {
$sql="insert into sohu (image,title,content) values('".$value['image']."','".$value['title']."','".$value['content']."')";
$pdo->exec($sql);
}
var_dump($data);
?>