Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: json decode limits

Tags:

json

php

Take this code:

$json = file_get_contents($this->url, true); 
$decode = json_decode($json, true); 

foreach ($decode as $key => $value) {
 ...
}

Pretty simple, uh?

Passing a $json with up to 500 array elements.... works right!

Above that limit... the error is:

Warning: Invalid argument supplied for foreach() in /c/website/retriever/WsGlassRetriever.php on line 19

Is there some memory limit for that function's argument?

I didn't found nothing about it in the docs. My version is PHP 5.2.17-rnx1.1 with Suhosin-Patch 0.9.7 (cli)

like image 231
Fabio B. Avatar asked Mar 28 '12 13:03

Fabio B.


2 Answers

json_decode returns NULL if there is an error in the JSON syntax. I've just successfully tested on an array of 1000 elements and it ran just fine.

Double-check that your JSON is correctly formatted. Even something as small as having single quotes instead of double, or forgetting to put a property name in quotes, or using a character outside the 32-127 range without correctly encoding it in UTF-8 can cause these problems.

like image 53
Niet the Dark Absol Avatar answered Sep 26 '22 23:09

Niet the Dark Absol


Am sure your JSON code above 500 has a formatting issue , have used JSON with over 20,000 values here is a simple script of 2000 array

$string = "Sample String Data ¶";
$string = preg_replace( '/[^[:print:]]/', '',$string); // remove all values that can affect JSON 
$array = array();
for($i = 0 ; $i <  2000; $i++)
{
    if(mt_rand(0, 1))
    {
        $array[] = $string ;
    }
    else
    {
        $array[] = array($string,1,$string) ;
    }
}   

$json =  json_encode($array);
$decodeArray =  json_decode($json);

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
        break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
        break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
        break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
        break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
        break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
    default:
        echo ' - Unknown error';
        break;
}

echo "<br />" ;


foreach ($decodeArray as $key => $value) {
    print_r($value) ;
    flush();
}

Edit 2

I was so interested to know if there is any limitation .. just tested it with 250,000 (Two hundred and fifty thousand values and it works fine )

Thanks Oleku

like image 20
Baba Avatar answered Sep 24 '22 23:09

Baba