在php中实时解析json响应

在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.

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
    );
}