当前位置:首页 > PHP教程 > php图像处理 > 列表

php自动保存文章内容中的图片

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-01 16:50:53 浏览: 评论:0 
  1. <?php  
  2. /*  
  3. author: ssh_kobe  
  4. date: 20110602  
  5. shortage: 如果网页中的图片路径不是绝对路径,就无法抓取  
  6. */  
  7. set_time_limit(0);//抓取不受时间限制 
  8.  
  9. $URL='http://pp.baidu.com/';//任意网址 
  10.  
  11. get_pic($URL); 
  12.  
  13. function get_pic($pic_url) {  
  14. //获取图片二进制流  
  15. $data=CurlGet($pic_url);  
  16. /*利用正则表达式得到图片链接*/  
  17. $pattern_src = '/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg]))['|"].*?[/]?>/';  
  18. $num = preg_match_all($pattern_src, $data, $match_src);  
  19. $arr_src=$match_src[1];//获得图片数组  
  20. get_name($arr_src); 
  21.  
  22. echo "<br>finished!!!";  
  23. return 0;  
  24. } 
  25.  
  26. /*得到图片类型,并将其保存到与该文件同一目录*/  
  27. function get_name($pic_arr)  
  28. {  
  29. //图片类型  
  30. $pattern_type = '/(/.(jpg|bmp|jpeg|gif|png))/'; 
  31.  
  32. foreach($pic_arr as $pic_item){//循环取出每幅图的地址  
  33. $num = preg_match_all($pattern_type, $pic_item, $match_type);  
  34. $pic_name = get_unique().$match_type[1][0];//改时微秒时间戳命名  
  35. //以流的形式保存图片  
  36. $write_fd = @fopen($pic_name,"wb");  
  37. @fwrite($write_fd, CurlGet($pic_item));  
  38. @fclose($write_fd);  
  39. echo "[OK]..!";  
  40. }  
  41. return 0;  
  42. } 
  43.  
  44. //通过微秒时间获得唯一ID  
  45. function get_unique(){  
  46. list($msec, $sec) = explode(" ",microtime());  
  47. return $sec.intval($msec*1000000);  
  48. } 
  49.  
  50. //抓取网页内容  
  51. function CurlGet($url){  
  52. $url=str_replace('&','&',$url);  
  53. $curl = curl_init();  
  54. curl_setopt($curl, CURLOPT_URL, $url);  
  55. curl_setopt($curl, CURLOPT_HEADER, false); 
  56.  
  57. //curl_setopt($curl, CURLOPT_REFERER,$url);  
  58. curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");  
  59. curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookie.txt');  
  60. curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookie.txt');  
  61. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
  62. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);  
  63. $values = curl_exec($curl);  
  64. curl_close($curl);  
  65. return $values;  
  66. }  
  67. ?> 

Tags: php自动保存 内容图片

分享到: