Select specific Tumblr XML values with PHP

拟墨画扇 提交于 2019-12-06 11:32:00

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

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.'" />';
}

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";
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!