这里有新鲜出炉的 PHP 面向对象编程,程序狗速度看过来!
PHP(外文名: Hypertext Preprocessor,中文名:"超文本预处理器")是一种通用开源脚本语言。语法吸收了 C 语言、Java 和 Perl 的特点,入门门槛较低,易于学习,使用广泛,主要适用于 web 开发领域。PHP 的文件后缀名为 php。
这篇文章主要介绍了 PHP 通过 CURL 实现定时任务的图片抓取功能, 涉及 php 的 curl 及 dom 操作相关技巧, 需要的朋友可以参考下
本文实例讲述了 PHP 通过 CURL 实现定时任务的图片抓取功能。分享给大家供大家参考,具体如下:
下文为各位介绍一个 PHP 定时任务通过 CURL 图片的抓取例子, 希望例子对大家帮助, 基本思路就是通过一个 URL 连接, 将所有图片的地址抓取下来, 然后循环打开图片, 利用文件操作函数下载下来, 保存到本地, 并且把图片的 alt 属性也抓取下来, 最后将数据保存到自己数据库.
废话不多说, 看程序就能明白了, 其中, 需要用到 PHP 定时任务和 PHP 的一个第三方插件 simple_html_dom.php 的使用, 参考 simple_html_dom 的下载和使用.
- <?php
- function getLink($url){
- include_once('simple_html_dom.php');
- $ch = curl_init();
- curl_setopt($ch,CURLOPT_URL,$url);
- curl_setopt($ch,CURLOPT_HEADER,false);
- curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
- $output = curl_exec($ch);
- curl_close($ch);
- $html = new simple_html_dom();
- $html->load($output);
- $links = array();
- $arr = array();
- $title = array();
- foreach($html->find('a') as $element){
- if(preg_match('#^\/content_[0-9]+_1\.html$#i',$element->href)){
- array_push($links,'http://www.phperz.com'.$element->href);
- array_push($title,$element->title);
- }
- }
- $links = array_values(array_unique($links));
- $title = array_values(array_unique($title));
- $arr['links'] = $links;
- $arr['title'] = $title;
- return $arr;
- }
- function loadimg($url,$dirname){
- include_once('simple_html_dom.php');
- $ch = curl_init();
- curl_setopt($ch,CURLOPT_URL,$url);
- curl_setopt($ch,CURLOPT_HEADER,false);
- curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
- $output = curl_exec($ch);
- curl_close($ch);
- $html = new simple_html_dom();
- $html->load($output);
- $arr = array();
- foreach($html->find('img[w]') as $element){
- $image = $element->src;
- }
- $data = file_get_contents($image);
- $info = getimagesize($image);//获取图片信息,大小,格式
- switch($info[2]){
- case 1:
- $str = 'gif';
- break;
- case 2:
- $str = 'jpg';
- break;
- case 3:
- $str = 'png';
- break;
- default:
- continue;
- break;
- }
- if($info[1] < 10 || $info[0] < 10) continue;//图片太小,不是有价值的图片,跳过本次循环
- $filename = time().rand(1,999999).'.'.$str;
- if(!is_dir($dirname)){
- mkdir($dirname,0777,true);
- }
- $fp = fopen($dirname.$filename,'w');
- fwrite($fp,$data);
- fclose($fp);
- return $dirname.$filename;
- }
- do{
- set_time_limit(0);
- ignore_user_abort();
- $img = getLink('http://www.phperz.com/qutu_1.html');
- $count = count($img['links']);
- $arr = array();
- for($i=0;$i<$count;$i++){
- $arr[]=loadimg($img['links'][$i],'images/');
- }
- $img['url'] = $arr;
- echo '<br/>';
- $img['title'];
- $res = array();
- $len = count($img['title']);
- //重新将数据组装成我们常用的二维数组,方便数据的数据库处理
- for($i=0;$i<$len;$i++){
- $res[$i]['title'] = $img['title'][$i];
- $res[$i]['url'] = $img['url'][$i];
- }
- foreach($res as $item){
- echo '<img src='.$item["url"].'>'.$item["title"].'<br />';
- }
- $interval = 24*3600;
- sleep($interval);
- }while(true);
- ?>
希望本文所述对大家 PHP 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0806/342284.html