PHP 从富文本获取图片地址

PHP·后端 · 03-06
    function getImageSrc($html_content){

        // 创建一个 DOMDocument 对象并加载 HTML 内容
        $dom = new \DOMDocument();
        $dom->loadHTML($html_content);
        // 获取所有的 <img> 标签
        $images = $dom->getElementsByTagName('img');

        // 定义一个数组来存储图片的 URL
        $image_urls = array();

        // 遍历每个 <img> 标签,提取 src 属性值
        foreach ($images as $image) {
            $src = $image->getAttribute('src');
            $image_urls[] = $src;
        }
        return $image_urls;
    }

出现错误:解决PHP 7异常:Warning: DOMDocument::loadHTML(): Tag ‘figure, nav, section’ invalid

使用其他方法获取 composer require symfony/dom-crawler

    function Crawler($html_content)
    {
        if (empty($html_content)) return [];

        $crawler = new Crawler($html_content);
        $images = $crawler->filterXPath('//img/@src')->each(function (Crawler $node, $i) {
            return $node;
        });
        $image_urls = [];
        foreach ($images as $image) {
            $image_urls[] = $image->text();
        }
        return $image_urls;
    }

解决PHP 7异常:Warning: DOMDocument::loadHTML(): Tag ‘figure, nav, section’ invalid

DOMDocument
Theme Jasmine by Kent Liao