Home > Backend Development > PHP Tutorial > Use php to batch download web page images to local code instance

Use php to batch download web page images to local code instance

PHP中文网
Release: 2023-02-28 09:34:01
Original
3990 people have browsed it

We now need to copy the content with pictures on other people’s websites to our own website, so I have to download the pictures from other people’s websites, then save them locally, and then replace the picture addresses in the content with our local ones. Here we need to Just use the three functions preg_match_all, file_get_contents, and str_replace in php.

<script>ec(2);</script>
Copy after login

I copied an article and found that the image paths are from other people’s websites. How can I download these images to the local with one click and modify them to the local paths?

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy(&#39;copy6124&#39;)">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy6124>/**
 * 获取替换文章中的图片路径
 * @param string $xstr 内容 采集网页的content
 * @param string $keyword 创建照片的文件名 我写upimg
 * @param string $oriweb 网址 一般写null
 * @return string
 * 
 */
function replaceimg($xstr,$keyword, $oriweb){ 
 $basedir = dirname(__FILE__);
 
    //保存路径
    $d = date(&#39;Ym&#39;, time());
    $dirslsitss = $basedir.&#39;/../uploads/&#39;.$keyword.&#39;/&#39;.$d;//分类是否存在
    if(!is_dir($dirslsitss)) {
        @mkdir($dirslsitss, 0777);
    }
    //匹配图片的src
    preg_match_all(&#39;#<img.*?src="([^"]*)"[^>]*>#i&#39;, $xstr, $match);
    foreach($match[1] as $imgurl){
        $imgurl = $imgurl;
        if(is_int(strpos($imgurl, &#39;http&#39;))){
            $arcurl = $imgurl;
        } else {
            $arcurl = $oriweb.$imgurl;        
        }
        $img=file_get_contents($arcurl);
        if(!empty($img)) {
            //保存图片到服务器
            $fileimgname = time()."-".rand(1000,9999).".jpg";
            $filecachs=$dirslsitss."/".$fileimgname;
            $fanhuistr = file_put_contents( $filecachs, $img );
            $saveimgfile = "/uploads/$keyword"."/".$d."/".$fileimgname;
            $xstr=str_replace($imgurl,$saveimgfile,$xstr);
        }
    }
    return $xstr;
}</td> </tr> </table></td> </tr> </table>
Copy after login
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template