Select specific Tumblr XML values ​​using PHP

My goal is to embed Tumblr messages in a website using the provided XML. The problem is that Tumblr saves 6 different sizes for each image you publish. My code below will get the first image, but it is too large. How can I select one of the smaller photos from XML if all the photos have the same <photo-url> ?

β†’ This is the XML from my Tumblr that I use: Tumblr XML .

β†’ This is my PHP code:

 <?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>"; ?> 
+2
source share
3 answers

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>"; } 
+1
source

To get a photo using 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.'" />'; } 
+1
source

Perhaps it:

 $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"; } } 
0
source

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


All Articles