您的当前位置:首页>全部文章>文章详情

PHP利用 simple_html_dom 远程图片本地化

发表于:2024-10-31 17:42:19浏览:286次TAG: #PHP #图片本地化 #爬虫 #采集

废话少说,直接上代码

在控制器中引入 simple_html_dom 库

use voku\helper\HtmlDomParser;

定义获取指定页面的文章内容和图片本地化

一般用于网页内容爬取

/**
     *@description 数据列表
     *@buildcode(false)
     */
    function getWebContent(){
        // 获取远程网页内容
        $url = 'http://www.news.cn/tech/20240520/f5652ab6026e48028e89234b7cd60eaa/c.html';
        // 获取当前网页路径,用于图片获取
        $parsedUrl = parse_url($url);
        $path = $parsedUrl['path'];
        $directoryPath = dirname($path);
        $fullPathWithoutFileName = $parsedUrl['scheme']. '://'. $parsedUrl['host']. $directoryPath;

        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );
        $html = file_get_contents($url, false, stream_context_create($arrContextOptions));
        $filename = 'ok.html';
        file_put_contents($filename, $html);
        $dom = HtmlDomParser::str_get_html($html);
        $elements  = $dom->find('div#detail');
        // 查找图片
        $images = $elements->find('img');

        $localImg = [];
        foreach ($images as $image) {
            $remoteImageUrl = $image->src;
            if (strpos($remoteImageUrl, 'http://') === 0 || strpos($remoteImageUrl, 'https://') === 0) {
                $imgFile = $remoteImageUrl;
            } else {
                $imgFile = $fullPathWithoutFileName.'/'.$remoteImageUrl;
            }
            $localImg[] = $imgFile;
            $localFileName = './backup/'. basename($remoteImageUrl);
            // 获取远程图片内容
            $imgContent = file_get_contents($imgFile);
            file_put_contents($localFileName, $imgContent);
        }


        $data['content'] = $elements ->innerhtml[0];
        $data['img'] = $localImg;
        return $data;
        $html->clear();
    }