I am trying to get the first image of each post of a feed. An image is always exists inside each <description>
as below
<description><p><a href="http://开发者_Go百科lh5.ggpht.com/-kDNySEwupXc/Tesp_XbEXQI/AAAAAAAAKZY/t5TMtq7SkCs/s1600-h/image%25255B4%25255D.png">< ....></description>
I get the title, author and other content as below
foreach ($entries as $entry) {
echo "<pre>"; echo $entry->title; echo" -- "; echo $entry->author; echo" -- "; echo $entry->pubDate; echo"<br>"; echo "</pre>";
}
but I do not know if the image is an attribute inside the description. If it is so how can I show it? I guess this solution is much easier and faster than using a regular expression like this one to get the first image :
preg_match('!http://.+\.(?:jpe?g|png|gif)!Ui'
If the regex is the only solution, how can I use it ?
Thank you
You could do the always reliable method of using a DOM parser.
$dom = new DOMDocument;
$dom->loadXML(html_entity_decode($entry->description));
$imageSrc = $dom->getElementsByTagName('a')->item(0)->getAttribute('href');
CodePad.
You may want to expand the code a bit to handle missing a
element (check lengtg
property) or missing href
attribute (use hasAttribute()
method).
精彩评论