php获取网页中图片并保存到本地

php获取网页中图片并保存到本地的代码,将网页中图片保存本地文件夹:

1 <?php

2 /**

3 * 获取网页中图片,并保存至本地

4 * by www.jbxue.com

5 */

6 header("Content-type:image/jpeg");

7 function read_url($str)

8 {

9 $file=fopen($str,"r");

10 while(!feof($file))

11 {

12 $result.=fgets($file,9999);

13 }

14 fclose($file);

15 return $result;

16

17 }

18

19 function save_img($str)

20 {

21 $result=read_url($str);

22 $result=str_replace("\"","",$result);

23 $result=str_replace("\'","",$result);

24

25 preg_match_all('/<img\ssrc=(http:\/\/.*?)(\s(.*?)>|>)/i',$result,$matches);

26

27 foreach($matches[1] as $value)

28 {

29 echo $value."<br>\n";

30 //GrabImage($value,$filename="");

31 }

32 }

33

34 // $url 是远程图片的完整URL地址,不能为空。

35 // $filename 是可选变量: 如果为空,本地文件名将基于时间和日期

36 // 自动生成.

37

38 function GrabImage($url,$filename="") {

39 if($url==""):return false;endif;

40

41 $path="download/"; //指定存储文件夹

42

43 //若文件不存在,则创建;

44 if(!file_exists($path)){

45 mkdir($path);

46 }

47

48 if($filename=="") {

49 $ext=strrchr($url,".");

50 if($ext!=".gif" && $ext!=".jpg"):return false;endif;

51 $filename=$path.date("dMYHis").$ext;

52 }

53

54 ob_start();

55 readfile($url);

56 $img = ob_get_contents();

57 ob_end_clean();

58 $size = strlen($img);

59

60 $fp2=@fopen($filename, "a");

61 fwrite($fp2,$img);

62 fclose($fp2);

63

64 return $filename;

65 }

66 save_img("http://www.jbxue.com");

67 ?>