Riya Shah
Riya Shah

Reputation: 167

get value from jsonp using php

I have jsonp like below

jsonp([
{"id":"HK\/HKD","bid":"40.14700","ask":"40.24300","high":"40.19500","low":"0.00000","vol":"0.03"},
{"id":"AUD\/JPY","bid":"58.69800","ask":"58.78200","high":"58.74000"}])

I am trying to get data from it using json_decode but its not working fine for me. I want get value of

HK/HKD called ask

and

AUD/JPY called ask

But I am not able to get it. Let me know if anyone can help me for get it. Thanks!

Upvotes: 0

Views: 26

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57141

With the extra jsonp( and the closing ), you would need to strip these off before decoding them. Just use substr() to remove these before decoding them...

$json = 'jsonp([
{"id":"HK\/HKD","bid":"40.14700","ask":"40.24300","high":"40.19500","low":"0.00000","vol":"0.03"},
{"id":"AUD\/JPY","bid":"58.69800","ask":"58.78200","high":"58.74000"}])';

$json = substr($json, 6, strlen($json)-7);
print_r(json_decode($json, true));

gives...

Array
(
    [0] => Array
        (
            [id] => HK/HKD
            [bid] => 40.14700
            [ask] => 40.24300
            [high] => 40.19500
            [low] => 0.00000
            [vol] => 0.03
        )

    [1] => Array
        (
            [id] => AUD/JPY
            [bid] => 58.69800
            [ask] => 58.78200
            [high] => 58.74000
        )

)

Even better would be to try and have these parts removed at the source of the data.

Upvotes: 1

Thomas
Thomas

Reputation: 88

<?php
  $items = json_decode('[{"id":"HK\/HKD","bid":"40.14700","ask":"40.24300","high":"40.19500","low":"0.00000","vol":"0.03"},
  {"id":"AUD\/JPY","bid":"58.69800","ask":"58.78200","high":"58.74000"}]');

  foreach ($items as $item) {
  var_dump($item->id);
}

It works for me. Can you try this?

Upvotes: 0

Related Questions