json_decode transforms dot in comma

MultiformeIngegno

  • Posts: 1,337
json_decode transforms dot in comma
« 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.

Arantor

  • As powerful as possible, as complex as necessary.
  • Posts: 14,278
Re: json_decode transforms dot in comma
« Reply #1, 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.
When we unite against a common enemy that attacks our ethos, it nurtures group solidarity. Trolls are sensational, yes, but we keep everyone honest. | Game Memorial

MultiformeIngegno

  • Posts: 1,337
Re: json_decode transforms dot in comma
« Reply #2, 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.. ?

Arantor

  • As powerful as possible, as complex as necessary.
  • Posts: 14,278
Re: json_decode transforms dot in comma
« Reply #3, 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.

MultiformeIngegno

  • Posts: 1,337
Re: json_decode transforms dot in comma
« Reply #4, 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. :)

Arantor

  • As powerful as possible, as complex as necessary.
  • Posts: 14,278
Re: json_decode transforms dot in comma
« Reply #5, 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 ;)