Search code examples
phpxmltumblr

Select specific Tumblr XML values with PHP


My goal is to embed Tumblr posts into a website using their provided XML. The problem is that Tumblr saves 6 different sizes of each image you post. My code below will get the first image, but it happens to be too large. How can I select one of the smaller-sized photos out of the XML if all the photos have the same tag of <photo-url>?

→ This is the XML from my Tumblr that I'm using: Tumblr XML.

→ This is my PHP code so far:

<?php
$request_url = "http://kthornbloom.tumblr.com/api/read?type=photo";
$xml = simplexml_load_file($request_url);
$title = $xml->posts->post->{'photo-caption'};
$photo = $xml->posts->post->{'photo-url'};
echo '<h1>'.$title.'</h1>';
echo '<img src="'.$photo.'"/>"'; 
echo "…";
echo "</br><a target=frame2 href='".$link."'>Read More</a>"; 
?>

Solution

  • The function getPhoto takes an array of $photos and a $desiredWidth. It returns the photo whose max-width is (1) closest to and (2) less than or equal to $desiredWidth. You can adapt the function to fit your needs. The important things to note are:

    • $xml->posts->post->{'photo-url'} is an array.
    • $photo['max-width'] accesses the max-width attribute on the <photo> tag.

    I used echo '<pre>'; print_r($xml->posts->post); echo '</pre>'; to find out $xml->posts->post->{'photo-url'} was an array.

    I found the syntax for accessing attributes (e.g., $photo['max-width']) at 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>"; 
    }