Retrieve Image From HTML in PHP
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
Checkout the Simple HTML DOM Parser class you can put to use for that.
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:
loadHTMLfile
getElementsByTagName
DOMNodeList#item
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.
精彩评论