PHP Returning Numeric Values in JSON
Note: This article was originally published at Planet PHP on 25 May 6460.joind.in API, quite a few people started to try it out. My friend David Soria Parra emailed me to point out that many of the numbers in the API were being returned as strings. He said:
It's just a standard problem of PHP REST services. When I try to access it with java I have to convert it over and over again to ints.
I did have a quick look at the PHP manual page for json_encode but I didn't see anything mentioning this. A few weeks later (my inbox is a black hole and it takes a while to process these things) I fell over a throwaway comment to an undocumented constant JSON_NUMERIC_CHECK, and I added the constant name to my todo list. In the time it took for me to actually get around to googling for this, some wonderful person updated the PHP manual page (this is why I love PHP) to include it as a documented option, and someone else had added a user contributed note about using it.
It turns out, this constant does exactly what I need. Here's a simple use case:
echo json_encode(array('event_id' = '603'));
echo json_encode(array('event_id' = '603'), JSON_NUMERIC_CHECK);
and the output:
There are probably some situations in which you don't want all your looks-like-a-number data to be returned as a number, but for now it seems to be a good fit for api.joind.in.