Joe W
Joe W

Reputation: 1008

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'); ?></p>

Thanks!

Upvotes: 1

Views: 4943

Answers (2)

Josh Davis
Josh Davis

Reputation: 28730

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);

Upvotes: 2

Igor Milla
Igor Milla

Reputation: 2786

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

Upvotes: 1

Related Questions