我的目标是使用 Tumblr 提供的 XML 将 Tumblr 帖子嵌入到网站中。问题是 Tumblr 会保存您发布的每张图片的 6 种不同尺寸。我下面的代码将获取第一张图像,但它恰好太大。如果所有照片都具有相同的标签 <photo-url>
,如何从 XML 中选择一张较小尺寸的照片?
→ 这是我正在使用的 Tumblr 中的 XML:Tumblr XML .
→ 这是我到目前为止的 PHP 代码:
<?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>";
?>
最佳答案
函数getPhoto
接受 $photos
的数组和一个 $desiredWidth
。它返回 max-width
的照片(1) 最接近且 (2) 小于或等于 $desiredWidth
。您可以调整该功能以满足您的需求。需要注意的重要事项是:
-
$xml->posts->post->{'photo-url'}
是一个数组。 -
$photo['max-width']
访问max-width
<photo>
上的属性标签。
我用过echo '<pre>'; print_r($xml->posts->post); echo '</pre>';
找出$xml->posts->post->{'photo-url'}
是一个数组。
我在 $photo['max-width']
的文档中找到了访问属性的语法(例如 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>";
}
关于php - 使用 PHP 选择特定的 Tumblr XML 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853851/