Handling big user IDs returned by FQL in PHP

后端 未结 6 2177
时光说笑
时光说笑 2020-11-29 09:30

I\'m using FQL to retrieve a list of users from Facebook. For consistency I get the result as JSON. This causes a problem - since the returned JSON encodes the user IDs as n

相关标签:
6条回答
  • 2020-11-29 09:44

    Quick and dirty, seems to work for now :

    $sJSON = preg_replace('/:(\d+)/', ':"${1}"', $sJSON);
    
    0 讨论(0)
  • 2020-11-29 09:46

    json_decode() can convert large integers to strings, if you specify a flag in the function call:

    $array = json_decode($json, true, 512, JSON_BIGINT_AS_STRING)
    
    0 讨论(0)
  • 2020-11-29 09:46

    I've resolved the issue by adding &format=json-strings to my the FQL api call, like so:

    $myQuery = "SELECT uid2 FROM friend WHERE uid1=me()";
    $facebook->api("/fql?q=" . urlencode($myQuery) . "&format=json-strings")
    

    This tells facebook to wrap all the numbers in quotes, which leads json_decode to use neither int-s not floats.

    Because I was afraid this issue is not restricted to FQL but to all graph API calls that choose to represent some of the IDs as BIG-INTs I've went as far as patching facebook's PHP SDK a bit to force Facebook to return all of its numbers as strings.

    I've added this one line to the _graph function. This would be line 738 in facebook_base.php, version 3.1.1

    $params['format'] = 'json-strings';
    

    Sure fix

    0 讨论(0)
  • 2020-11-29 09:46

    I use this and it works almost great.

    json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $jsonString), true)
    

    The json breaks when there is geo data included, eg. {"lat":54.2341} results in "lat":"54".2341

    Solution:

    $json = preg_replace('/("\w+"):(\d+)(.\d+)?/', '\\1:"\\2\\3"', $json);
    
    0 讨论(0)
  • 2020-11-29 09:59

    I had a similar problem where json_decode was converting recent twitter/tweet IDs into exponential numbers.

    Björn's answer is great if you want your BIGINT to become a string - and have PHP 5.3+. If neither of those things are true, another option is to up PHP's float precision. This can be done a different few ways...

    • find the precision value in your php.ini and change it to precision = 20
    • add ini_set('precision', 20); to your PHP app
    • add php_value precision 20 to your app's .htaccess or virtual host file
    0 讨论(0)
  • 2020-11-29 10:08

    This (preg_replace('/("\w+"):(\d+)(.\d+)?/', '\\1:"\\2\\3"', $json);) worked for me (for parsing result from facebook api)

    0 讨论(0)
提交回复
热议问题