PbootCMS---二开实现采集富文本图片

最近在用PbootCMS做采集功能,采集了约10万篇内容,但是有些内容的图片是远程图片,需要采集到本地来,以下是具体的实现方法:

/**
 * [saveimg 下载远程图片]
 */
public function saveimg($min = 0,$max = 0)
{
    // $id = 1664;
    // $infos = parent::table('ay_content')->where("id={$id}")->find();
    // $data = [
    //     'content' => $this->formateImgContent($infos->content)
    // ];
    // $this->modContent($infos->id,$data);
    $list = parent::table('ay_content')->where('id>='.$min.' AND id<='.$max)->select();
    foreach($list as $item){
        $data = [
            'content' => $this->formateImgContent($item->content)
        ];
        $this->modContent($item->id,$data);
    }
}
/**
 * [formate 格式化图片富文本]
 */
public function formateImgContent($str = null)
{
    if(!$str) return $str;
    $content = htmlspecialchars_decode($str);
    $imgs = $this->getImgs($content);
    if(empty($imgs)) return;
    foreach($imgs as $item){
        $saveimg = $this->downloadimg($item);
        if($saveimg){
            $saveimg = '/' . $saveimg;
            $content = str_replace($item,$saveimg,$content);
        }
    }
    return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
}
/**
 * 下载远程图片
 */
public function downloadimg($imgpath)
{        
    $imgarr = explode('.', $imgpath);
    $imgext = end($imgarr);
    $rand = rand(1000, 10000);
    $filename = md5(time() . rand(1000,10000) . rand(1000,10000)) . '.' . $imgext;
    $save = 'static/upload/image/20240716/' . '78-' . $filename;
    $image = file_get_contents($imgpath);
    $result = file_put_contents($save, $image);
    return $result ? $save : null;
}
/**
 * 获取富文本里面的图片
 */
public function getImgs($content,$order = 'ALL')
{
    $pattern ="/<img .*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
    preg_match_all($pattern,$content,$match);
    if(isset($match[1]) && !empty($match[1])){
        if($order==='ALL'){
            return $match[1];
        }
        if(is_numeric($order) && isset($match[1][$order])){
            return $match[1][$order];
        }
    }
    return  [];
}

打完收工!

posted @ 2024-07-15 18:53  帅到要去报警  阅读(2)  评论(0编辑  收藏  举报