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

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
