Search code examples
phpweb

Web scraping photo in PHP


How do I copy the url for the photo from the site if the url written in styles.

<div class="thumb">
               <a href="http://goruzont.blogspot.com/2017/04/blog-post_6440.html" style="background:url(https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg) no-repeat center center;background-size:cover">

<span class="thumb-overlay"></span></a>
 </div>

Solution

  • You can use regex to extract only background image or background:url format

    $str=' 
    <div class="thumb">
                   <a href="http://goruzont.blogspot.com/2017/04/blog-post_6440.html" style="background:url(https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg) no-repeat center center;background-size:cover">
    
    <span class="thumb-overlay"></span></a>
     </div>'; 
    
    preg_match_all('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$str,$matches);
    $images = $matches['image'];
    foreach($images as $img){
         echo $img;
    }
    # https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg