开发者

Get Tumblr post title using API & PHP?

Using this post and the Tumblr API, I'm trying to embed the title of whatever the latest blog entry is on my website.

For some reason, I thought this would be a nice simple code, but it returns empty. Have I missed something obvious?

// Contents of includes/latest_blog.php
<?php
  $request_url = 'http://###NAME###.tumblr.com/api/read?start=0&num=1';
  $xml = simplexml_load_file($request_url);
  $title = $xml->posts->post->{‘regular-title’};
  $link = $xml->posts->post[‘url’];
  echo 'Latest blog entry: <a href="'.$link.'">'.$title.'</a>';
?>

The website:

<p class="blog_title"><?php include('includes/latest_blog.php开发者_StackOverflow中文版'); ?></p>

Thanks!


Actually the code is fine, it's just that you're using fancy Unicode quotation marks as in‘regular-title’ instead of the ASCII single-quote as in 'regular-title'.

Incorrect:

$title = $xml->posts->post->{‘regular-title’};
$link = $xml->posts->post[‘url’];

Correct:

$title = $xml->posts->post->{'regular-title'};
$link = $xml->posts->post['url'];

For some reason, you must have missed the error message, so make sure you see all errors while testing new code:

ini_set('display_errors', true);
error_reporting(-1);


You where on the right way. Here is the code (it works, but i cannot find working solution to make it without foreach), but anyway you should remember that tittle is an optional field, and it could be empty string, so you will need to check it before building a link tag.

$request_url = 'http://YOURNAME.tumblr.com/api/read?start=0&num=1';
$xml = simplexml_load_file($request_url);
$posts = $xml->xpath("/tumblr/posts/post"); 
foreach($posts as $post) {
  $url = $post['url-with-slug'];
  $tittle = $post->{'regular-title'};
  echo '<a href="'.$url.'">'.$tittle.'</a>';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜