douxun4173
2014-12-22 20:49
采纳率: 0%
浏览 21
已采纳

使用php从URL获取JSON对象

I have from url this

[{"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":[]}]

and my php is this

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

I try to remove the brackets from the url and the code run but i get it with brackets... How can i remove them?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drhg24275 2014-12-22 20:59
    已采纳
    <?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>';
    ?>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqk42179 2014-12-22 20:52

    $obj is an array with 1 element.

    The short fix is, do $obj = $obj[0] first.

    Then you can do $obj["user_id"] etc.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题