使用php从URL获取JSON对象

时间:2014-12-22 20:49:16

标签: php json

我来自网址

[{"user_id":"3932131","username":"DanielDimitrov","count300":"1677134","count100":"239025","count50":"41207","playcount":"17730","ranked_score":"1413977663","total_score":"7355146958","pp_rank":"35848","level":"95.5852","pp_raw":"1582.26","accuracy":"97.88556671142578","count_rank_ss":"42","count_rank_s":"337","count_rank_a":"120","country":"BG","events":[]}]

我的php就是这个

$json = file_get_contents('url');
    $obj = json_decode($json);
    echo $obj->user_id;
    echo 'Username: '.$obj['username'].'<br>';
    echo 'PP: '.(int)$obj['pp_raw'].'<br>';
    echo 'Level: '.(int)$obj['level'].'<br>';
    echo 'Play count: '.$obj['playcount'].'<br>';

我尝试从网址中移除括号并运行代码但是我用括号将其删除...如何删除它们?

2 个答案:

答案 0 :(得分:0)

$obj是一个包含1个元素的数组。

简短的解决方法是先行$obj = $obj[0]

然后你可以$obj["user_id"]等。

答案 1 :(得分:0)

<?php
$json = '[{"user_id":"3932131","username":"DanielDimitrov","count300":"1677134","count100":"239025","count50":"41207","playcount":"17730","ranked_score":"1413977663","total_score":"7355146958","pp_rank":"35848","level":"95.5852","pp_raw":"1582.26","accuracy":"97.88556671142578","count_rank_ss":"42","count_rank_s":"337","count_rank_a":"120","country":"BG","events":[]}]';
    $in = array("[{", "}]");
    $out = array("{", "}");
    $obj = json_decode(str_replace($in, $out, $json));
    echo $obj->user_id;
    echo 'Username: '.$obj->username.'<br>';
    echo 'PP: '.(int)$obj->pp_raw.'<br>';
    echo 'Level: '.(int)$obj->level.'<br>';
    echo 'Play count: '.$obj->playcount.'<br>';
?>