3

I'm trying to debug a PHP application, and as a section of the debug process, I passed print_r($GLOBALS) through the AJAX request to my browser. However, I'd prefer to see it in native JSON form because it comes out better in the browser. I'm trying to use the following snippet of code:

json_encode($GLOBALS);

but I've found it returns bool(false). The JSON documentation says "Returns a JSON encoded string on success or FALSE on failure." But what about $GLOBALS makes it fail? Is it the recursive $GLOBALS['GLOBALS']?

I was thinking as an alternative to loop over $GLOBALS and put that in an array, but that seems quite pointless when the point of json_encode is to encode an array.

4 Answers 4

5

Upon testing this myself, it appears json_encode() can't handle recursion such as what's provided in $GLOBALS['GLOBALS']... etc.

So a trick(?) you can do is:

json_encode(array_slice($GLOBALS, 1));

Which will skip past $GLOBALS['GLOBALS'] and continue encoding the rest of the array.

*EDIT: $GLOBALS['GLOBALS'] appears first for me when printing this array, but a better way is to find where $GLOBALS['GLOBALS'] appears and skip that element entirely.

6
  • int(6) - message is "Recursion detected". I think you just got the number wrong for array_slice(), what you did slices one from the beginning.
    – iggyvolz
    Apr 19, 2014 at 21:44
  • You just missed a parameter, it should be json_encode(array_slice($GLOBALS, 0, -1));
    – iggyvolz
    Apr 19, 2014 at 21:45
  • @iggyvolz my goal was to skip the first element which is $GLOBALS['GLOBALS'] hence I made the offset argument 1 (which is the second parameter according to PHP docs) and continues for the rest of the array. But if it works for you then I can't complain. Apr 19, 2014 at 21:51
  • I ended up using this: $globals_dump = $GLOBALS; unset($globals_dump['GLOBALS']); // You might also have to unset($globals_dump['globals_dump']); depending on if you are in a function
    – iggyvolz
    Apr 19, 2014 at 21:56
  • @iggyvolz ah, well I guess that doesn't help either of us! :P Anyway, there are ways to just ignore that particular element anyway if you needed a fail-safe version (assuming you're working directly with $GLOBALS). Apr 19, 2014 at 21:58
3

I propose a way where the position of GLOBALS is not important:

json_encode(array_intersect_key($GLOBALS,array_flip(array("_GET", "_POST", "_FILES", "_COOKIE"))));

or a better way:

$new_array = $GLOBALS;
$index = array_search('GLOBALS',array_keys($new_array));
json_encode(array_splice($new_array, $index, $index-1));
3
  • Doesn't this require you to hard-code all elements from $GLOBALS you want? What about global variables? codepad.org/VRTHyEtp Apr 19, 2014 at 22:06
  • Yep. I did it now by just typing the index you would like to remove.
    – barbarity
    Apr 19, 2014 at 22:12
  • 1
    concept is the same but I like the implementation of the second snippet better than mine. +1 Apr 19, 2014 at 22:17
0

The fact that $GLOBALS contains reference to itself results in an infinite recursion that json_encode can't handle because it exceeds the maximum depth of 512 and thus will return false by default.

The solution would be creating a copy of $GLOBALS without self-referencing, the function below references superglobals _GET _POST _SERVER .. only, assuming you don't use $_ in your variables naming conventions:

function getEncodableGlobals()
{
    $g = [];

    foreach ($GLOBALS as $key => &$val)
    {
        if ($key[0] == '_')
        {
            $g[$key] = &$val;
        }
    }

    return $g;
}

Notice that $g doesn't hold copies but only references to variables, just like $GLOBALS does. If you wish to include all the variables in the global scope simply change the condition to exclude the troublesome reference:

...
    if ($key !== 'GLOBALS')
...

Now you can safely encode it:

json_encode(
    getEncodableGlobals()
);

You could also do it the array_filter way and copy the variables.

$encodableGlobals = array_filter($GLOBALS, function($key) {
    return $key !== 'GLOBALS';
}, ARRAY_FILTER_USE_KEY);
0

json_encode can't handle recursion such as what's provided in $GLOBALS['GLOBALS']... etc.

JSON.stringify is same! you will retrieve error : JSON.stringify error because recursion

So in php you can create a new variable, example $globals which holds an array of $GLOBALS.

And, unset the recursive $globals['GLOBALS'].

$globals = $GLOBALS;
unset($globals['GLOBALS']);
echo json_encode($globals);

And... Congrats!! Now you can json_encode $GLOBALS variable!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.