PHP 获取 HTML 文档里的所有图片链接

PHP

测试代码

<p><img src="https://dn-phphub.qbox.me/uploads/images/201701/25/1/dxcDfZsjA0.jpg?imageView2/1/w/1024/h/546" alt="" /></p>
<p>文档地址在此:<a href="https://laravel-china.org/docs/5.4">https://laravel-china.org/docs/5.4</a></p>
<p>翻译的召集帖:<a href="https://laravel-china.org/topics/3810">https://laravel-china.org/topics/3810</a></p>
<p>参与人员列表:<a href="https://laravel-china.org/roles/11">Laravel 5.4 译者</a></p>
<p>项目托管在 Github 上,欢迎提交反馈:<a href="https://github.com/laravel-china/laravel-docs">https://github.com/laravel-china/laravel-docs</a></p>
<blockquote>
<p>我代表 Laravel 中文文档的受益者对 可爱的 <a href="https://laravel-china.org/roles/11">Laravel 5.4 译者</a> 表示感谢 :beer:   :metal:</p>
</blockquote>
<p><a href="https://laravel-china.org/users/1814">@徐小花</a> 分享的离线版本: <a href="https://laravel-china.org/topics/4026">https://laravel-china.org/topics/4026</a> </p>
<p><img src="https://dn-phphub.qbox.me/uploads/images/201610/19/1/F9kV4goXoU.png" alt="" /></p>

函数 get_images

function get_images($html)
{
    $doc = new DOMDocument();
    @$doc->loadHTML($html);

    $img_tags = $doc->getElementsByTagName('img');
    $result = [];
    foreach ($img_tags as $img) {
        $result[] = $img->getAttribute('src');
    }
    return $result;
}

结果

array:2 [▼
  0 => "https://dn-phphub.qbox.me/uploads/images/201701/25/1/dxcDfZsjA0.jpg?imageView2/1/w/1024/h/546"
  1 => "https://dn-phphub.qbox.me/uploads/images/201610/19/1/F9kV4goXoU.png"
]
评论数量: 0

4
点赞
488
浏览
0
评论

贡献 538
Summer
Building Products Users Love