Is the image an attribute or do I need to use a regular expression to get it?

I am trying to get the first image of each feed post. An image always exists inside each <description> , as shown below.

 <description>&lt;p&gt;&lt;a href="http://lh5.ggpht.com/-kDNySEwupXc/Tesp_XbEXQI/AAAAAAAAKZY/t5TMtq7SkCs/s1600-h/image%25255B4%25255D.png"&gt;&lt; ....></description> 

I get the title, author and other content below

 foreach ($entries as $entry) { echo "<pre>"; echo $entry->title; echo" -- "; echo $entry->author; echo" -- "; echo $entry->pubDate; echo"<br>"; echo "</pre>"; } 

but I don’t know if the image is an attribute inside the description. If so, how can I show it? I think this solution is much simpler and faster than using a regular expression like this to get the first image:

 preg_match('!http://.+\.(?:jpe?g|png|gif)!Ui' 

If regex is the only solution, how can I use it?

thanks

+4
source share
1 answer

You can always make a reliable method for using the DOM parser.

 $dom = new DOMDocument; $dom->loadXML(html_entity_decode($entry->description)); $imageSrc = $dom->getElementsByTagName('a')->item(0)->getAttribute('href'); 

CodePad

You might want to extend the code a bit to handle the missing element a (check the lengtg property) or the href attribute is missing (use the hasAttribute() method).

+1
source

All Articles