background image

gd 库图片下载类实现下载网页所有图片的 php 代码

在前期的

php 教程就讲了 php gd 库可以实现远程图片的下载,但是那只是下载了一张图片,

原理是一样的,要想下载一个网页的所有图片只要使用正则表达式进行判断,找出所有的
图片

url 就可以进行循环下载了,我特地参照网络资源编写了 gd 库图片下载类!

php 代码如下: 
代码如下

:

 
<?php 
header("Content-type:text/html ; charset=utf-8"); 

if

 (!

empty

(

$_POST

['submit'])){ 

$url

 = 

$_POST

['url']; 

//为了获取相对路径的图片所做的操作 

$url_fields

 = 

parse_url

(

$url

); 

$main_url

 = 

$url_fields

['host']; 

$base_url

 = 

substr

(

$url

,0,

strrpos

(

$url

, '/')+1); 

//获取网页内容 
//设置代理服务器 

$opts

 = 

array

('http'=>

array

('request_fulluri'=>true)); 

$context

 = stream_context_create(

$opts

); 

$content

 = 

file_get_contents

(

$url

,false,

$context

); 

//匹配 img 标签,将所有匹配字符串保存到数组$matches 

$reg

 = "/<img.*?src=\"(.*?)\".*?>/i"; 

preg_match_all(

$reg

$content

$matches

); 

$count

 = 

count

(

$matches

[0]); 

for

 (

$i

=0; 

$i

<

$count

$i

++){ 

/*将所有图片的 url 转换为小写 
*$matches[1][$i] = strtolower($matches[1][$i]); 
*/

 

//如果图片为相对路径就转化为全路径 
if

 (!

strpos

('a'.

$matches

[1][

$i

], 'http')){ 

//因为'/'是第 0 个位置 
if

 (

strpos

('a'.

$matches

[1][

$i

], '/')){ 

$matches

[1][

$i

] = '

http://§

'.

$main_url

.

$matches

[1][

$i

]; 

}

else

$matches

[1][

$i

] = 

$base_url

.

$matches

[1][

$i

]; 



//过滤重复的图片 

$img_arr

 = 

array_unique

(

$matches

[1]);