Search code examples
phphtmlcssxpathdomxpath

How to get background image from internal css using xpath?


I want to get background-image URL that is in internal css. I'm using xpath in php

Here is the html structure

<div id="plugin-title" class="with-banner">
<div class="vignette"></div>

<style type="text/css">
#plugin-title { width:772px; height:250px; background-size:772px 250px; background-image: url(//ps.w.org/jetpack/assets/banner-772x250.png?rev=1279667); }
</style>
<h2 itemprop="name">Jetpack by WordPress.com</h2>
</div>

Solution

  • If you want the links for background-image, then you can use this RegExp.

    background-image.*?url\((.*?)\)
    

    Example implementation:

    $html = <<<EOT
    <div id="plugin-title" class="with-banner">
        <div class="vignette"></div>
        <style type="text/css">
        #plugin-title { width:772px; height:250px; background-size:772px 250px; background-image: url(//ps.w.org/jetpack/assets/banner-772x250.png?rev=1279667); }
        </style>
        <h2 itemprop="name">Jetpack by WordPress.com</h2>
    </div>
    EOT;
    
    preg_match_all('/background-image.*?url\((.*?)\)/mi', $html, $matches);
    

    $matches contains all the background-image urls.