Question

I had so many web site addresses which have images I want to have. I want to know the image source at that web site.

Below is my php code. but that doesn't work.

  <?php
  $html = array('url1', 'url2', ...);
  $result = "";
  preg_match_all('/<img[^>]+>/i', $html, $result);
  echo $result;
  ?>

Please, Would you complete above incomplete code?

Was it helpful?

Solution

You better off with DOMDocument Class , Never use Regex as a parser for parsing HTML Content.

$htmlsourceofthewebsite = file_get_contents('http://www.somewebsite.com');
$dom = new DOMDocument;
$dom->loadHTML($htmlsourceofthewebsite);
foreach ($dom->getElementsByTagName('img') as $tag) {
        echo $tag->getAttribute('src');
    }
}

OTHER TIPS

You should not use regex to parse html content. Use DOMDocument.

Try like this:

$html=array('url1', 'url2', ........); // your url array

        foeach($html as $a){ //run a loop through your array
          getImage($a); // get images

        }

       function getImage($url){           
        $dom = new DOMDocument;
        $dom->loadHTML($url);
        foreach ($dom->getElementsByTagName('img') as $t) {
                echo $t->getAttribute('src');
             }
          }   
       }

Document: http://www.php.net/manual/en/class.domdocument.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top