tags:

views:

38

answers:

3

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

+2  A: 

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

Sarfraz
+1  A: 

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
+1  A: 

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
[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