user3294179
user3294179

Reputation: 21

Cant get value from JSON

I need some help accessing an api. http://market.huobi.com/staticmarket/detail.html in PHP.

$json = file_get_contents("http://market.huobi.com/staticmarket/detail.html"); 
$obj = json_decode($json);

Below is a small sample of the api response.

$obj =
{
    "sells": [
        {
            "price": 3840,
            "level": 0,
            "amount": 1
        },
        {
            "price": "3840.05",
            "level": 0,
            "amount": 0.287
        },
        {
            "price": 3841,
            "level": 0,
            "amount": 0.1
        } ],
 "p_new": 3838,
    "level": -72.12,
    "amount": 82792,
    "total": 321774060.34653,
    "amp": -2,
    "p_open": 3910.12,
    "p_high": 3925,
    "p_low": 3809.99,
    "p_last": 3910.12
}

            echo "Ask     " . $obj->sells[0]->price; // does not work
            echo "Volume" . $obj->amount;// does not work

Help will be appreciated.

Upvotes: 0

Views: 109

Answers (1)

Barmar
Barmar

Reputation: 780724

The API you're calling is returning JSONP data, not JSON data.

JSONP data looks like:

somefunction(JSONdata)

You need to remove the function call wrapper.

$jsonp = file_get_contents("http://market.huobi.com/staticmarket/detail.html");
preg_match('/^.*?\((.*)\)/s', $jsonp, $match);
$json = $match[1];
$obj = json_decode($json);

echo "Ask     " . $obj->sells[0]->price . '<br>';
echo "Volume  " . $obj->amount;

Upvotes: 1

Related Questions