Home  >  Article  >  Backend Development  >  使用PHP实现下载CSS文件中的图片_php实例

使用PHP实现下载CSS文件中的图片_php实例

WBOY
WBOYOriginal
2016-06-07 17:10:38779browse

作为一个资深并且专业的扒皮人员,在我从初三开始投入伟大的互联网中到现在积累了丰富的扒皮经验。我相信每个做web的程序员也都会有类似的经历。

在扒皮过程中,必不可少的需要下载样式文件中的图片。碰到比较庞大的样式文件,其中可能会有上百个需要下载的图片,那么使用下面这段小代码是最为合适的了。

< &#63;php
/*
 More & Original PHP Framwork
 Copyright (c) 2007 - 2008 IsMole Inc.

 Author: kimi
 Documentation: 下载样式文件中的图片,水水专用扒皮工具
*/

//note 设置PHP超时时间
set_time_limit(0);

//note 取得样式文件内容
$styleFileContent = file_get_contents('images/style.css');

//note 匹配出需要下载的URL地址
preg_match_all("/url\((.*)\)/", $styleFileContent, $imagesURLArray);

//note 循环需要下载的地址,逐个下载
$imagesURLArray = array_unique($imagesURLArray[1]);
foreach($imagesURLArray as $imagesURL) {
 file_put_contents(basename($imagesURL), file_get_contents($imagesURL));
}

再给大家分享一段封装好的类

/** 
* 获取CSS中图片地址,并且保存到本地 
*/
class getInCssImage
{ 
/** 
* 图片保存下来
* @param $cssUrl css的url地址
* @param $dir 保存图片的目录
* @return void
*/
static public function saveImage($cssUrl, $dir)
{ 
$content = file_get_contents($cssUrl); 
$patterns = '/images(.*).(jpg|gif|png)/'; //正则根据不同地址需要变换
preg_match_all($patterns, $content, $matches);
$imagesUrls = $matches[0];
if (!is_dir($dir))
mkdir(dirname(__FILE__). '/'. $dir, 0777);
foreach($imagesUrls as $image)
{ 
ob_start();
$imageUrl = "http://www.xx.com/".$image; //这个地址本来用程序给获取的。偷懒了下
readfile($imageUrl);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);
$localImage = $dir. strchr($image, '/'); //存到本地的图片地址
$fp = fopen($localImage, 'a');
fwrite($fp, $img);
fclose($fp);
} 
} 
}
}
$content = getInCssImage::saveImage('/css/css.css', 'image');

最后预祝各位在扒皮的过程中,一扒到底!

另外附上关于file_put_contents定义和用法

file_put_contents() 函数把一个字符串写入文件中。
与依次调用 fopen(),fwrite() 以及 fclose() 功能一样。

语法

file_put_contents(file,data,mode,context)

参数 描述

file 必需。规定要写入数据的文件。如果文件不存在,则创建一个新文件。
data 可选。规定要写入文件的数据。可以是字符串、数组或数据流。
mode 
可选。规定如何打开/写入文件。可能的值:
FILE_USE_INCLUDE_PATH
FILE_APPEND
LOCK_EX
context 
可选。规定文件句柄的环境。
context 是一套可以修改流的行为的选项。若使用 null,则忽略。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn