Now we want to copy the content with images from other websites to our website. in this way, I have to download images from other websites and save them to my local computer, replace the image address in the content with our local address. here we need to use the three functions preg_match_all, file_get_contents, and str_replace in php. Now we want to copy the content with images from other websites to our website. in this way, I have to download images from other websites and save them to my local computer, replace the image address in the content with our local address. here we need to 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 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: |
|
/*** Get the path of the image in the replacement article * @ param string $ xstr content collection webpage content * @ param string $ the file name of the photo created by keyword I wrote upimg * @ param string $ oriweb generally, the URL is 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);} // 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 (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 ;} |