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
  • 17,849
  • 40
  • 101
  • 129

3 Answers3

2

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

Sarfraz
  • 367,681
  • 72
  • 526
  • 573
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
  • 87,377
  • 14
  • 113
  • 114
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
  • 10,643
  • 3
  • 41
  • 59
  • [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