2011-03-01 30 views
1

使用this后和Tumblr API,我试图嵌入任何最新的博客条目在我的网站上的标题。使用API​​和PHP获取Tumblr发布标题?

出于某种原因,我认为这将是一个不错的简单代码,但它会返回空白。我错过了明显的东西吗?

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

网站:

<p class="blog_title"><?php include('includes/latest_blog.php'); ?></p> 

谢谢!

回答

2

其实代码是好的,它只是你用花哨的Unicode引号作为‘regular-title’代替ASCII单引号作为'regular-title'

错误:

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

正确:

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

出于某种原因,你必须已经错过了错误信息,所以确保你看到所有的错误,同时测试新代码:

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

你在正确的路上。这里是代码(它工作,但我找不到工作的解决方案,使其无需foreach),但无论如何,你应该记住,tittle是一个可选字段,它可能是空字符串,所以你需要检查它之前建立一个链接标签。

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