Facebook Batch Requests and PHP json_decode bug in php 5.2.x + Solution
Join the DZone community and get the full member experience.
Join For FreeI've been working on one of my facebook apps (www.fbtab.net) and had to do some optimizations by combining multiple requests in one batch request.
The idea is to encode the requests in JSON then decode the result JSON data.
Facebook IDs are usually big integers and because of a bug in php 5.2.+ json library the ID gets converted to float numbers.
Solution: parse the JSON buffer and prefix every integer in the buffer
with a string then enclose the new string in quotes that way the JSON
parser won't convert the integers into the float numbers. Then Decode
and manually remove the added string prefix.
Here is an example how to get the current user data and the pages that user is currently administrating.
Note: make sure you replace APP_ID, APP_API_SECRET_KEY with your app's app id and secret key.
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_API_SECRET_KEY,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
$pages = null;
$login_url = null;
$logout_url = null;
// Session based API call.
if ($session) {
try {
$queries = array(
array('method' => 'GET', 'relative_url' => 'me'),
array('method' => 'GET', 'relative_url' => 'method/fql.query?query='
. urlencode("SELECT page_id, name, pic_small, page_url, has_added_app FROM page WHERE page_id IN "
. "(SELECT page_id FROM page_admin WHERE uid = me())")
),
);
$batch_arr = $facebook->api('/?batch=' . json_encode($queries), 'POST');
// the current user data is [0]; with php 5.2 it cannot decode long ints so we'll make them strings
if (!empty($batch_arr[0]['body']) && $batch_arr[0]['code'] == 200) {
if (version_compare(PHP_VERSION, '5.3.0') < 0) {
$batch_arr[0]['body'] = preg_replace('#(id"\:)(\d+)#siu', '\\1"SYS\\2"', $batch_arr[0]['body']);
}
$me = json_decode($batch_arr[0]['body'], true);
$me['id'] = str_replace('SYS', '', $me['id']);
}
// the current user data is [1]; with php 5.2 it cannot decode long ints so we'll make them strings
if (!empty($batch_arr[1]['body']) && $batch_arr[1]['code'] == 200) {
if (version_compare(PHP_VERSION, '5.3.0') < 0) {
$batch_arr[1]['body'] = preg_replace('#(id"\:)(\d+)#siu', '\\1"SYS\\2"', $batch_arr[1]['body']);
$pages = json_decode($batch_arr[1]['body'], true);
foreach ($pages as $key => $value) {
$pages[$key]['page_id'] = str_replace('SYS', '', $pages[$key]['page_id']);
}
} else {
$pages = json_decode($batch_arr[1]['body'], true);
}
}
$logout_url = $facebook->getLogoutUrl();
} catch (FacebookApiException $e) {
error_log($e);
}
}
From http://www.devcha.com/2011/05/facebook-batch-requests-and-php.html
Opinions expressed by DZone contributors are their own.
Comments