开发者

Is the image an attribute or I have to use a regex to get it?

开发者 https://www.devze.com 2023-03-12 01:19 出处:网络
I am trying to get the first image of each post of a feed. An image is always exists inside each <description> as below

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>&lt;p&gt;&lt;a href="http://开发者_Go百科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 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消