php批量下载网页图片并替换路径为本地
我们现在要复制别人网站上的带有图片的内容到自己网站,这样我必须下载别人网的图片,然后保存到本地,再把内容中的图片地址替换成我们本地的,这里我们要借助于php中preg_match_all,file_get_contents,str_replace三个函数即可。
一篇文章复制过来,发现图片路径都是别人网站的,如何一键下载这些图片到本地,并且修改成为本地的路径呢。
代码如下 | 复制代码 |
/** * 获取替换文章中的图片路径 * @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('# ![]() 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; } |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
