【问题标题】:Detect node from html string and extract image inside in PHP从 html 字符串中检测节点并在 PHP 中提取图像
【发布时间】:2016-09-18 18:24:53
【问题描述】:

我锁定了一些让我发疯的东西,如果你能帮助我,那就太好了!

我有一个包含有效 HTML 代码的字符串。在这个 PHP 代码中,我想通过他的父类检测一个特定的图像,并提取图像的 url + 用另一个 url 更新它。

这是一个例子:

$html = '....<div class="header">...<img src="theimage.png" />...</div>...';

我想解析 $html 字符串,提取 url "theimage.png" 并用 "theimage2.png" 替换它(经过一些内部工作)

我尝试使用 REGEX,但我不确定它是否是最佳解决方案,因为我需要确保只返回 .header 中的图像,并且我需要执行一些函数来获取名称未来的链接。

也许解决办法是用 DOM Node 解析 HTML,但也没有用。

你能帮帮我吗?谢谢!!!

【问题讨论】:

  • 您想要一个不使用任何第三方API的答案吗??

标签: php html string dom


【解决方案1】:

您可以使用SimplePHPDom 实现此目的

PHP

$html = '<body><div class="header"><p>some html</p><img src="theimage.png" /></div></body>';
$html_dom = str_get_html($html);

foreach($html_dom->find('.header img') as $element) {
    echo $element->src . '<br>'; // output src of img inside .header div
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-08
    • 2020-07-29
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2021-01-01
    • 2013-02-03
    • 2015-02-03
    相关资源
    最近更新 更多