Tumblr API如何从php中的以下数组访问各个值

时间:2011-11-21 15:01:26

标签: php api multidimensional-array tumblr

我正在使用tumblr API和以下代码:

$var = xhttp::toQueryArray($response['body']);
print_r($var);

此屏幕上的内容如下:

Array ( [{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"lukebream","likes":0,"following":8,"default_post_format":"html","blogs":[{"name":"lukebream","url":"http:\/\/lukebream.tumblr.com\/","followers":5,"primary":true,"title":"Untitled","admin":true,"queue":0,"ask":false,"tweet":"N"}]}}}] => )

如何访问各个元素并将它们分配给变量?

以下是我的完成内容:

$tumblr->set_token($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$data = array();
$data['post'] = array();        
$response = $tumblr->fetch('http://api.tumblr.com/v2/user/info', $data);    

if($response['successful']) {
    echo $response['json']['response']['url'];
} else {
    echo "api call failed. {$response[body]}<br><br>";
}

2 个答案:

答案 0 :(得分:0)

它名为JSON,您可以使用json_decode()

解析它

用法示例:

//I used file_get_contents() to keep things simple
$jsonData = file_get_contents("http://api.tumblr.com/v2/blog/lukebream.tumblr.com/info?api_key=<api_key_here>"); 

$ jsonData包含:

{
    "meta":{
        "status":200,
        "msg":"OK"
        },
    "response":{
        "blog":{
            "title":"Untitled",
            "posts":61,
            "name":"lukebream",
            "url":"http:\/\/lukebream.tumblr.com\/",
            "updated":1321830278,
            "description":"",
            "ask":false,
            "likes":0
            }
        }
}

经过json_decode()后,我们得到一个PHP对象,所以:

$obj = json_decode($jsonData);

将返回:

stdClass Object
(
    [meta] => stdClass Object
        (
            [status] => 200
            [msg] => OK
        )
    [response] => stdClass Object
        (
            [blog] => stdClass Object
                (
                    [title] => Untitled
                    [posts] => 61
                    [name] => lukebream
                    [url] => http://lukebream.tumblr.com/
                    [updated] => 1321830278
                    [description] => 
                    [ask] => 
                    [likes] => 0
                )
        )
)

然后您可以像访问任何其他对象一样访问数据。

答案 1 :(得分:0)

你也可以使用json_decode($ str,TRUE):这将返回一个ARRAY而不是一个对象,更容易玩!