dongzhong5756 2014-08-24 12:30
浏览 65
已采纳

在php中实时解析json响应

I am working on a research project for my graduate program in finance regarding crypto currencies (bitcoin,etc) . I am trying to parse out individual objects from JSON responses produced by cryptsy (market for exchanging crypto currencies) api(https://www.cryptsy.com/pages/privateapi). I am using the API example code given by cryptsy which can be found in the URL provided above. I would like to grab my account balances for starters. your help here would be very much appreciated.

The responses I am getting look like this:

Array
(
    [success] => 1
    [return] => Array
        (
            [balances_available] => Array
                (
                    [42] => 0.00000000
                    [AGS] => 0.00000000
                    [ALN] => 0.00000000
                    [ALF] => 0.00000000
                    [AMC] => 0.00000000

My code I am trying to write not working so well:

$result = api_query("getinfo");
$json = file_get_contents($result);
$json2 = json_decode($json, true);
foreach($json2->attachments->balances_available AS $attach) {
    file_put_contents('test.txt', $attach, FILE_APPEND);

}

echo "<pre>".print_r($json2, true)."</pre>";

Error Message:

Warning: file_get_contents() expects parameter 1 to be a valid path, array given in /Users/Aditya/Desktop/PHP-1.php on line 45

Warning: Invalid argument supplied for foreach() in /Users/Aditya/Desktop/PHP-1.php on line 47

Any help would be very much appreciated, I have looked all over every forum and I am not a computer science guy. Once again thank you for your time and patience.

  • 写回答

1条回答 默认 最新

  • doudou890510 2014-08-24 21:50
    关注

    The sample api_query method already returns an array:

    $array = api_query("getinfo");
    

    Therefore you need to apply neither file_get_contents nor json_decode on the $result variable.

    It's a plain array at this point, so just [] accesses, no -> property traversal. I'm not sure it's wrapped in ["attachments"] anyway. See var_dump($array) for the actual structure.

    You can just loop over it:

    foreach ($array["attachments"]["balances_available"] as $key => $value) {
        print " $key == $value 
    <br>";
    }
    

    If you want to store it into an file (you may wish to elaborate on the format), then append it likewise:

    foreach (/* as seen above*/) {
        file_put_contents(
            'test.txt',
            " $key has $value balance 
    ",
            FILE_APPEND
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器