kthornbloom
kthornbloom

Reputation: 3720

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>"; 
?>

Upvotes: 2

Views: 1004

Answers (3)

creemama
creemama

Reputation: 6665

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>"; 
}

Upvotes: 1

flowfree
flowfree

Reputation: 16462

To get the photo with max-width="100":

$xml = simplexml_load_file('tumblr.xml');

echo '<h1>'.$xml->posts->post->{'photo-caption'}.'</h1>';

foreach($xml->posts->post->{'photo-url'} as $url) {
    if ($url->attributes() == '100')
        echo '<img src="'.$url.'" />';
}

Upvotes: 1

ioseb
ioseb

Reputation: 16951

Maybe this:

$doc = simplexml_load_file(
  'http://kthornbloom.tumblr.com/api/read?type=photo'
);

foreach ($doc->posts->post as $post) {
  foreach ($post->{'photo-url'} as $photo_url) {
    echo $photo_url;
    echo "\n";
  }
}

Upvotes: 0

Related Questions