Using PHP to extract img src alt and title from HTML

Using PHP to extract img src alt and title from HTML is quite easy and this can be done in two ways. Either using PHP regular expression matching or using the Document Object Model (DOM).

Using regexp to extract img tags is a bad idea and will likely lead in unmaintainable and unreliable code.

Using DOM: Here is a DOMDocument/DOMXPath based example to extract img src alt and title from HTML using PHP.

Assuming you have URL of the page:

And if you have html content ready then the idea is same. I just used xpath as an example:

Use of the DOMDocument::loadHTML() method can cope with HTML-syntax and does not force the input document to be XHTML. Therefore simpleXMLElement is not necessary – it just makes using xpath and the xpath results more simple using PHP to extract img src alt and title from HTML.

You Might Interested In

1 COMMENT

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.