A Flickr feed is very useful when we want to retrieve our images uploaded on a Flickr's album. Within this feed, we're only interested in the description
element contained inside each item
element. By default, all the content of this element is served as HTML and it's a little bit redundant because it also contains unnecessary information, such as "Gabriele Romanato posted a photo" repeated several times. Let's say that we want only the images, with no links or descriptions. How can we achieve this result?
PHP allows us to use Perl-Compatible Regular Expressions (PCRE) to select some portions inside strings or, more generally, textual content. So we're going to use them together with the SimpleXML library. Example:
$flickr_rss = simplexml_load_file('your/feed/url'); $entries = $flickr_rss->channel->item; $i = -1; $html = ''; $html .= '<div class="pics">' . "\n"; do { $i++; $entry = $entries[$i]; $content = $entry->description; $pre_content = preg_replace('/\n+|\r\n+/', '', $content); $img_src_re = preg_match_all('/src=".+"/', $pre_content, $matches); $src = str_replace('src="', '', $matches[0][0]); $html .= '<img src="' . $src . '" />' . "\n"; } while($i < 4); $html .= '</div>' . "\n"; echo $html;
We're actually retrieving only the first five images of our album using a do...while
loop. Since we know that the URL of each image is contained within a src
attribute, we use a regular expression to accomplish this task. Then we remove the src="
characters from the string using str_replace()
. Note that since we've used preg_match_all()
, the returned result is an array whose first value is in turn another array, so our value is contained in the first item of this second array.