Search code examples
phpxpathdomdocument

Extract value from background-image style attribute with PHP


I have a following HTML code:

<div class="article__img has-caption" style="background-image: url('img/main/article-plug.png')" >

I'm trying to extract an image URL and replace it with another (for example img/main/article-plug.webp) but I'm stuck with XPath queries and don't know what to do.

Thanks for help in advance!

That's my last code (but it doesn't return anything yet):

$domDocument = new DOMDocument();
$domDocument->loadHTML($article["DESCRIPTION"]);

$domXPath = new DOMXPath($domDocument);

$img = $domXPath->query('substring-before(substring-after(//div[@class=\'article__img has-caption\']/@style, "background-image: url(\'"), "\')")');  

Solution

  • Finally, with a help from dlporter98 I was able to solve my problem, here is a code if someone will face the same problem:

    $domDocument = new DOMDocument();
    $domDocument->loadHTML(mb_convert_encoding($html, "HTML-ENTITIES", "UTF-8"));
    
    $domXPath  = new DOMXPath($domDocument);
    $divs = $domXPath->evaluate("//div[@class=\"article__img has-caption\"]");
    foreach ($divs as $div) {
        $style = $div->getAttribute("style");
    
        $url = $domXPath->evaluate("substring-before(substring-after(@style, \"background-image: url('\"), \"')\")", $div);
    
        $div->setAttribute("style", str_replace($url, Webp::getFromUrl($url), $style));
    }
    
    $html = mb_convert_encoding($domDocument->saveHTML(), "UTF-8", "HTML-ENTITIES");