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.
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 area with one click and modify them to the local paths?
The code is as follows
代码如下 |
复制代码 |
/**
* 获取替换文章中的图片路径
* @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('#]*>#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;
} |
|
Copy code |
/** |
* Get the image path in the replacement article
* @param string $xstr content Collect the content of the web page
* @param string $keyword The file name of the created photo. I write upimg
* @param string $oriweb URL, usually write null
* @return string
*
*/
function replaceimg($xstr,$keyword, $oriweb){
$basedir = dirname(__FILE__);
//Save path
$d = date('Ym', time());
$dirslsitss = $basedir.'/../uploads/'.$keyword.'/'.$d;//Whether the category exists
If(!is_dir($dirslsitss)) {
@mkdir($dirslsitss, 0777);
}
// Match the src of the image
Preg_match_all('#
]*>#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)) {
//Save the picture to the server
$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;
}
http://www.bkjia.com/PHPjc/631508.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631508.htmlTechArticleWe now need to copy the content with pictures from other people’s websites to our own website, so I have to download the content from other people’s websites. Picture, then save it locally, and then replace the picture address in the content with...