0

Hey, so I have some html ok, and inside it there's a couple of images. What I want to do is retrieve the location of the first image from the html. (get the first images url)

How can I do this in PHP?

Thanks

Belgin Fish
  • 19,187
  • 41
  • 102
  • 131

3 Answers3

2

Checkout the Simple HTML DOM Parser class you can put to use for that.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

I would suggest taking a look at, DOMDocument.

Once you load the HTML into a DOMDocument you can easily traverse through the file and retrieve the first image url.

References:

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
1

You COULD use a regular expression (though html is NOT technically regex parseable as its not... regular): Read in the contents of the file, then use a regular expression to hopefully find the img tag and extract the src attribute. Definitely not the best solution, but a technically possible solution. I don't really recommend this.

Outside of that you may want to look into a PHP Document Object Model parser and find the first image node.

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
  • [This is why you should **never** use regex for parsing HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Joe D Oct 30 '10 at 19:26