php CSSファイルの画像アドレスを取得し、ローカルにダウンロードする方法

1697 ワード

この例では、phpがCSSファイルのピクチャアドレスを取得してローカルにダウンロードする方法について説明します.皆さんの参考にしてください.
実装コードは次のとおりです.
 
  
/** 
* 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.xxxx.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');

ここで述べたことが皆さんのPHPプログラム設計に役立つことを願っています.