I copied an article and found that the image paths are from other websites. How can I download these images to a local directory with one click and change them to a local path.
| The code is as follows: |
Copy code |
/**
* Obtain the image path in the replacement document.
* @ Param string $ xstr content of the webpage
* @ Param string $ the name of the file in which the keyword creates the photo. I wrote upimg.
* @ Param string $ oriweb URL is generally null
* @ Return string
*
*/
Function replaceimg ($ xstr, $ keyword, $ oriweb ){
$ Basedir = dirname (_ FILE __);
// Save path
$ D = date ('ymm', time ());
$ Dirslsitss = $ basedir. '/.../uploads/'. $ keyword. '/'. $ d; // whether the category exists
If (! Is_dir ($ dirslsitss )){
@ Mkdir ($ dirserver load balancer, 0777 );
}
// Match the image's 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 )){
// Save the image to the server
$ Fileimgname = time (). "-". rand (, 9999). ". jpg ";
$ Filecachs = $ dirslsitss. "/". $ fileimgname;
$ Fanhuistr = file_put_contents ($ filecachs, $ img );
$ Saveimgfile = "/uploads/$ keyword". "/". $ d. "/". $ fileimgname;
$ Xstr = str_replace ($ imgurl, $ saveimgfile, $ xstr );
}
}
Return $ xstr;
} |