Home > Article > Backend Development > Use php to batch download web page images to local code instance
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>
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('copy6124')">复制代码</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('Ym', time()); $dirslsitss = $basedir.'/../uploads/'.$keyword.'/'.$d;//分类是否存在 if(!is_dir($dirslsitss)) { @mkdir($dirslsitss, 0777); } //匹配图片的src preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $xstr, $match); foreach($match[1] as $imgurl){ $imgurl = $imgurl; if(is_int(strpos($imgurl, 'http'))){ $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>