3

A friend asked me a simple code to grab values from a website, no problem. This website is using a json API, again, no problem.

But, after parsing results I figured values were all wrong.

Example:

A value on the json is 846.51, but my script is returning 844.71.

My current "code":

$data = file_get_contents('https://blockchain.info/fr/ticker');
$json = json_decode($data);

print_r($json->{'USD'}->{'15m'});

So, I searched and i found out it may be a php bug related to x64 processors, not sure.

Any workaround to fix this ?

Daedalus
  • 7,586
  • 5
  • 36
  • 61
John Konolol
  • 69
  • 1
  • 9
  • I'm on a 64x machine and I'm experiencing no such problems. – Daedalus Nov 23 '13 at 22:31
  • 2
    Are you sure it's a bug of whatever sorts, and not just changing data or the wrong field being grabbed? – John Dvorak Nov 23 '13 at 22:31
  • 1
    The "related" column contains good related questions. [prevent php from parsing floats as floats in json_decode](http://stackoverflow.com/q/9497743), [PHP function json_decode decodes float value with zeros after point as int](http://stackoverflow.com/q/12531828) – Pekka Nov 23 '13 at 22:32
  • Yeah i checked multiple time, numbers from json and from json_decode are not the same, can't get why. json: "USD" : {"15m" : 846.51, "last" : 846.51, "buy" : 842.03, "sell" : 846.51, "symbol" : "$"} php: { "USD" : {"15m" : 840.07, "last" : 840.07, "buy" : 840.04, "sell" : 840.07, "symbol" : "$"} – John Konolol Nov 23 '13 at 22:32

2 Answers2

1

So ! It was indeed a php bug according to https://bugs.php.net/bug.php?id=50224

Here is the fixed version:

$data = file_get_contents('https://blockchain.info/fr/ticker');
$res = preg_replace( '/":(\d+)/', '":"\1"', $data );
$json = json_decode($res);

print_r($json->{'EUR'}->{'15m'});
John Konolol
  • 69
  • 1
  • 9
0

Improving answer from John Konolol : the regex will not work if the value is a floatting decimal number expressed in sci format ("2.038069541E9").

Regex must be :

preg_replace( '/":(\d+\.*\d*E*e*\d*)/', '":"\1"', $data)

It will convert all number to string, including float number (1.34) or sci format numer (1E3) which are valid in Json.

JayMore
  • 211
  • 5
  • 8