The getPhoto function takes an array of $photos and a $desiredWidth . It returns a photo for which max-width is (1) closest and (2) less than or equal to $desiredWidth . You can adapt the function to suit your needs. It is important to note:
$xml->posts->post->{'photo-url'} is an array.$photo['max-width'] refers to the max-width attribute in the <photo> .
I used echo '<pre>'; print_r($xml->posts->post); echo '</pre>'; echo '<pre>'; print_r($xml->posts->post); echo '</pre>'; to find out that $xml->posts->post->{'photo-url'} was an array.
I found syntax for accessing attributes (for example, $photo['max-width'] ) in the documentation for SimpleXMLElement .
function getPhoto($photos, $desiredWidth) { $currentPhoto = NULL; $currentDelta = PHP_INT_MAX; foreach ($photos as $photo) { $delta = abs($desiredWidth - $photo['max-width']); if ($photo['max-width'] <= $desiredWidth && $delta < $currentDelta) { $currentPhoto = $photo; $currentDelta = $delta; } } return $currentPhoto; } $request_url = "http://kthornbloom.tumblr.com/api/read?type=photo"; $xml = simplexml_load_file($request_url); foreach ($xml->posts->post as $post) { echo '<h1>'.$post->{'photo-caption'}.'</h1>'; echo '<img src="'.getPhoto($post->{'photo-url'}, 450).'"/>"'; echo "..."; echo "</br><a target=frame2 href='".$post['url']."'>Read More</a>"; }
source share