PHP, JSON and the Twitpocalypse
16 June 2009I recently had a problem using PHP’s json_decode() with Twitter’s search API. The Twitpocalypse meant that the tweet status ids were being limited to 2147483647, and in my case, any new tweets weren’t being saved as the app thought they already existed.
To get around the problem of json_decode() limiting ints, I added a regex replace to change large numbers to strings by adding quote marks around them. json_decode() then sees the number as a string and parses it correctly.
An example search function with the fix is shown below:
function TwitterSearch($query) {
$search_url = 'http://search.twitter.com/search.json?q='.$query;
$ch = curl_init($search_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$json = curl_exec($ch);
// -- int-max fix - convert number to string
$json = ereg_replace('([:])([0-9]{10})([,}])', '\\1"\\2"\\3', $json);
$result = json_decode($json);
curl_close($ch);
return $result;
}
The regex here only looks for 10-digit numbers, but this can easily be changed for larger numbers by changing the {10} to say {10,16} to catch 10 to 16 digit numbers.

Spotted these in John Lewis last weekend