0

所有,我有以下代码可以从 Tumblr 获取一些帖子:

$baseHostname = "name.tumblr.com";
$tumblrConsumerKey = "asfd"; # use your own consumer key here
$humblr = new Humblr($baseHostname, $tumblrConsumerKey);

$post = $humblr->getPosts(array('limit' => 1));
print_r($post);

这工作正常,并给了我这样的结果:

Array ( 
    [0] => stdClass Object ( 
        [blog_name] => name 
        [id] => 43993 
        [post_url] => http://name.tumblr.com/post/43993/
        [slug] => slug 
        [type] => video 
        [date] => 2013-02-25 18:00:25 GMT 
        [timestamp] => 1361815225 
        [state] => published 
        [format] => html )

我尝试显示一些像这样的值:

echo "The blog name is: ".$post->blog_name;
echo $post->id;

但是,它是空白的。如何显示这些值?

谢谢

4

2 回答 2

1

如我所见,它是一个数组,因此您可以尝试:

echo $post[0]->blog_name;
于 2013-02-25T18:17:50.520 回答
1

首先,打开错误报告

// error reporting for development environment
error_reporting(-1);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

正如@Zlatan 指出的那样,它是一stdClass。

启用错误报告后,您将收到此代码的错误通知“注意:尝试在...中获取非对象的属性” :

echo "The blog name is: ".$post->blog_name;
echo $post->id;

因为您正在尝试访问非对象。

您可以通过它的数组索引访问对象来修复它:

echo "The blog name is: ".$post[0]->blog_name;
echo $post[0]->id;

假设$posts

Array
(
    [0] => stdClass Object
        (
            [blog_name] => blog1
            [id] => 10234
            [post_url] => http://name.tumblr.com/post/43993/
            [slug] => slug
            [type] => video1
            [date] => 2013-02-25 18:00:25 GMT
            [timestamp] => 1361815225
            [state] => published
            [format] => html
        )

    [1] => stdClass Object
        (
            [blog_name] => blog2
            [id] => 20234
            [post_url] => http://name.tumblr.com/post/43993/
            [slug] => slug1
            [type] => video
            [date] => 2013-02-25 18:00:25 GMT
            [timestamp] => 1361815225
            [state] => published
            [format] => html
        )

)

通过数组索引访问对象:

echo "The blog name is: ".$post[0]->blog_name;
echo $post[0]->id;
echo "The blog name is: ".$post[1]->blog_name;
echo $post[1]->id;

// prints
// The blog name is: blog1
// 10234
// The blog name is: blog2
// 20234

如果要循环发布帖子:

foreach ($posts as $post) {
    echo "The blog name is: ".$post->blog_name;
    echo $post->id;
}

// prints
// The blog name is: blog1
// 10234
// The blog name is: blog2
// 20234

资源

于 2013-02-25T18:56:40.087 回答