7

I wanted a php script to fetch all the images in HTML code and list it. Can anyone help me do this, or some Idea as to how I should proceed ? I am new to this, so any help would be appreciated.

Aditya
  • 165
  • 1
  • 5
  • 10
  • 1
    Given the answers and the fact one has even been given 3 up votes, it would be good to accept the answer you like most so people get the appropriate recognition. – CogitoErgoSum Sep 03 '10 at 15:06

5 Answers5

8

you can use DOMDocument, or simplehtmldom. here is a DOMDocument example:

$dom = new DOMDocument();
$dom->loadHtml($yourHtmlAsAString);
foreach ($dom->getElementsByTagName('img') as $img) {
    echo $img->getAttribute('src').'<br>'; // or whatever you need
}
Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
4

Run the HTML code through one of the many HTML parser libraries and then query for the src attribute value on all the img elements.

Community
  • 1
  • 1
hao
  • 10,138
  • 1
  • 35
  • 50
3

Tried looking at DOMDocument in PHP? http://php.net/manual/en/domdocument.getelementsbytagname.php

Good example from that page:

$dom = new DomDocument();
$dom->prevservWhiteSpace = false;

$dom->loadHTML($htmlString);

$imageList = $dom->getElementsByTagName('img');
$imageCnt  = $imageList->length;

for ($idx = 0; $idx < $imageCnt; $idx++) {
    print $imageList->item($idx)->nodeValue . "\n";
}

Should give you the basics you need.

*Disclaimer, example is slightly modified from the comment I yanked it from but this is pretty straight forward stuff.

CogitoErgoSum
  • 2,879
  • 5
  • 32
  • 45
2

If you want to load it from an actual php/html file...

$dom = new DomDocument();

if (!@$dom->load('img.php')) {
    echo 'url does not exist';
    return;
}

$imgs = $dom->getElementsByTagName('img');

for ($buffer = ''; $i = 0, $len = $imgs->length; $i < $len; $i++)
{
  $buffer .= 'image ' . $i . ' is: ' . $imgs->item($i)->getAttribute('src') . '<br/>';
}

echo $buffer;
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • Thanks a lot eveyone for the code, it works just fine. Nw I knw DomDocument can do magic :) – Aditya Sep 02 '10 at 19:52
1

I would suggest looking into the DOM. It should provide the functionality you are looking for.

Jim
  • 18,673
  • 5
  • 49
  • 65