Wedge

Public area => The Pub => Off-topic => Topic started by: MultiformeIngegno on May 12th, 2013, 04:10 PM

Title: json_decode transforms dot in comma
Post by: MultiformeIngegno on May 12th, 2013, 04:10 PM
Here's the JSON input: http://pastebin.com/xGWtWb5P

I do a json_decode
Code: [Select]
<?php <a target="_blank" style="color:darkgrey" rel="nofollow" href="http://maps.google.com/maps?q='.htmlentities($value->location->latitude).',+'.htmlentities($value->location->longitude).'">mappa</a?>

But instead of dots for GPS coords it outputs commas... O_O
Original: LAT 41.917866942 LONG 12.873182618
json_decode: LAT 41,917866942 LONG 12,873182618

It's not htmlentities fault, I tried disabling it and it still outputs commas.
Title: Re: json_decode transforms dot in comma
Post by: Arantor on May 12th, 2013, 04:15 PM
Yay for locale settings!

json_encode/json_decode takes the floats as encoded into the JSON and converts them to your locale settings which IIRC will use commas rather than periods in Italian.

http://php.net/setlocale has a little bit more.
Title: Re: json_decode transforms dot in comma
Post by: MultiformeIngegno on May 12th, 2013, 10:01 PM
Uh! Right! I added a setlocale(LC_ALL, 'it_IT.UTF-8'); at the beginning of the file because I have other code that requires the locale setting.. How can I "overwrite" the locale just for these $value->location->latitude / $value->location->longitude.. ?
Title: Re: json_decode transforms dot in comma
Post by: Arantor on May 12th, 2013, 10:18 PM
I'd suggest setlocale(LC_NUMERIC, 'en_US.UTF-8');

Be careful with the trailing definition of charset, .utf8 is often suggested in preference to .UTF-8 and you can specify multiple types.
Title: Re: json_decode transforms dot in comma
Post by: MultiformeIngegno on May 12th, 2013, 10:21 PM
Quote from Arantor on May 12th, 2013, 10:18 PM
I'd suggest setlocale(LC_NUMERIC, 'en_US.UTF-8');

Be careful with the trailing definition of charset, .utf8 is often suggested in preference to .UTF-8 and you can specify multiple types.
Worked. :)
I remember I choose .UTF-8 because I checked and I had that exact string as installed-language.
Posted: May 12th, 2013, 10:20 PM

EDIT: I used setlocale(LC_TIME, 'it_IT.UTF-8'); and with this I don't need the NUMERIC directive. :)
Title: Re: json_decode transforms dot in comma
Post by: Arantor on May 12th, 2013, 10:24 PM
Yup, that makes sense, ideally only use what you need to convert. Interestingly, Wedge only calls setlocale on LC_TIME too, principally because we do our own number formatting, though perhaps we should reconsider that too ;)