PHP抓新闻

这是很久以前写的一个抓新浪新闻的东西了,目的是为了方便学校同学不花钱上内网看时事新闻。我是从新浪rss先抓取内容html网址,再进一步匹配标题,正文,图片……
今天又对代码做了点小改动:
//检查是否实视频,是视频则不抓取
if(strpos($title[1],"视频",0)!==false){//以前写的是!=
echo "不抓取视频!";
return false;
}
!==和!=,===和==他们的区别主要就是在判断值是否相等的同时,还要判断两者的类型。以前看书的时候看过,不过到还没真正应用到过自己的代码里面。
http://www.stuhome.net/readnews/ 这就是我以前写的那个抓新闻板块。



<?php
require_once(dirname(__FILE__)."/../global.php");
//抓取网页内容
set_time_limit(0);

$line = file_get_contents("http://rss.sina.com.cn/sports/basketball/nba.xml");
$line = strstr( $line, "<item>");

$line=explode("</item>",$line);

$count=count($line);
for($i=0;$i<$count;$i++){
eregi ("<pubDate>(.*)</pubDate>",$line[$i],$time);
//取得链结
if (eregi ("<link>(.*)</link>",$line[$i],$out)) {
$news = file_get_contents("$out[1]");
if(eregi ("<h1>(.*)</h1>",$news,$title)){ //匹配标题
preg_replace("/ /","",$title[1]); //去除标题中的空格
$title[1] = trim($title[1]);
$title[1]=strip_tags($title[1]); //去除标题中的的HTML标记
//$title[1] = addslashes($title[1]);

//检查是否实视频,是视频则不抓取
if(strpos($title[1],"视频",0)!==flase){
echo "不抓取视频!";
//exit;
return false;
}
echo $title[1];
echo "<br>";
}else{
$title[1]="";
}

$dt=getdate();
$hours=$dt[hours];
$publish_time=$dt[year]."-".$dt[mon]."-".$dt[mday]."-".$hours."-".$dt[minutes]."-".$dt[seconds];
if($title[1]!=""){
$sql_title="select title from news where title='$title[1]'";
$result=$DB->fetch_one_array($sql_title);
if(empty($result)){

//取出正文部分
$news = strstr($news,"<!--正文内容开始-->");
$news = explode("<!--正文内容结束-->", $news);


//匹配正文内容
if(eregi ("<p>(.*)</p>",$news[0],$content)){
echo $content[1];
echo "<br>";
}else{
$content[1]="";
}


//匹配图片路径
$picture_name="";
$img="";
$news=explode("border",$news[0]);
for($j=0;$j<count($news);$j++){
if(preg_match("/http:\/\/i(.*)\.(jpeg|png|jpg)/i",$news[$j],$picture)){
$img[$j]=GrabImage($picture[0],"");

if($img[$j]){
$imgpath[$j]=dirname(__FILE__)."/pictures/".$img[$j];
echo '<pre><img src='.$imgpath[$j].'></pre>';
}else{
$img[$j]="";
}
}else{
$picture[0]="";
$img[$j]="";
}
$picture_name.=$img[$j];
}

}
}
}
}

?>


<?php
// Function: 获取远程图片并把它保存到本地
// $url 是远程图片的完整URL地址,不能为空。
// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期自动生成.
function GrabImage($url,$filename="") {
if($url==""){
return false;
}
if($filename=="") {
$ext=strrchr($url,".");
$temext = strrchr(strtolower($url),".");
if($temext!=".jpg"&$temext!=".jpeg"){
return false;
}
$filename=date("dMYHis").$ext;
$filepath=dirname(__FILE__)."/pictures/".$filename;
}

ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);

$fp2=fopen($filepath, "a");
fwrite($fp2,$img);
fclose($fp2);

return $filename;
}
?>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值