How to extract URL from string in PHP?

I use PHP "simplexml_load_file" to get some data from Flickr.

My goal is to get the url of the photo.

I can get the following value (assigned to a PHP variable):

<p><a href="http://www.flickr.com/people/19725893@N00/">codewrecker</a> posted a photo:</p>

<p><a href="http://www.flickr.com/photos/19725893@N00/2302759205/" title="Santa Monica Pier"><img src="http://farm3.static.flickr.com/2298/2302759205_4fb109f367_m.jpg" width="180" height="240" alt="Santa Monica Pier" /></a></p>

How can I extract only this part?

http://farm3.static.flickr.com/2298/2302759205_4fb109f367_m.jpg

Just in case this helps, here is the code I'm working with:

<?php
$xml = simplexml_load_file("http://api.flickr.com/services/feeds/photos_public.gne?id=19725893@N00&lang=en-us&format=xml&tags=carousel");
foreach($xml->entry as $child) {
    $flickr_content = $child->content; // gets html including img url
    // how can I get the img url from "$flickr_content"???
 }
?>
+3
source share
4 answers

You may be able to use the regex for this, assuming that the way the HTML is generated remains pretty much the same, for example:

if (preg_match('/<img src="([^"]+)"/i', $string, $matches)) {
    $imageUrl = $matches[1];   
}

, HTML (, <img>, HTML ..), HTML-.

+6

(, , ), , 2 .

phpFlickr - http://phpflickr.com/

+1

: substr strpos , src= '...' , , .

( ROBUST): XML, ​​ simpleXML

0

, . xpath, XML, SimpleXML:

<?php
$xml = new SimpleXMLElement("http://api.flickr.com/services/feeds/photos_public.gne?id=19725893@N00&lang=en-us&format=xml&tags=carousel", NULL, True);
$images = $xml->xpath('//img');  //use xpath on the XML to find the img tags

foreach($images as $image){  
    echo $image['src'] ;  //here is the image URL
}
?>
0

Source: https://habr.com/ru/post/1713453/


All Articles