免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2050 | 回复: 1

php自动保存文章内容中的图片 [复制链接]

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

论坛徽章:
0
发表于 2012-01-23 02:04 |显示全部楼层
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP