PHP and json_decode() madness: json_decode() incorrectly handling large ints
This had me up the walls for a while. For the new Adapting to Scarcity website, I wrote some custom scripts to generate an RSS feed of our Flickr photos and photosets to facilitate automagically populating the website with our latest from Flickr. I've been passing some information in a JSON string, but was getting incorrect results after processing it. Turns out some versions of PHP 5 have a weird issue with the json_decode string improperly handling largest integers. Solution? Stop using integers and turn them into strings.
An example string of JSON that needed processing used to look like this:
{"id":72157623575805990,"primary_photo_id":4414877237}But look what happens using json_decode on that with PHP version 5.2.4-2ubuntu5.10:
php > $foo = '{"id":72157623575805990,"primary_photo_id":4414877237}';
php > var_dump(json_decode($foo, TRUE));
array(2) {
["id"]=>
int(72157623575805984)
["primary_photo_id"]=>
int(4414877237)
}Pay attention to the value of 'id'. It went from being 72157623575805990 to 72157623575805984. WTF?!
So, I modified my feed generator to wrap the integers inside of quotes to make json_decode() think it was a string. Semeed to solve the problem:
php > $foo = '{"id":"72157623575805990","primary_photo_id":"4414877237"}';
php > var_dump(json_decode($foo, TRUE));
array(2) {
["id"]=>
int(72157623575805984)
["primary_photo_id"]=>
int(4414877237)
}Quite frankly, I ought to upgrade my PHP (this appears to have been fixed in later [or at least some] versions). But you know, I don't got time for that right now.




Post new comment