<\/script>')

"safe" json_decode (,,) to prevent memory exhaustion

In my application, I often call an external api that returns a json string.

$url = 'api.example.com/xyz';
$blah = json_decode( file_get_contents( $url ) );

But in some cases I get

PHP Fatal error: allowable memory size xxx bytes exhausted (tried to allocate 32 bytes) in ...

I can not control the external API, and, of course, I could increase the memory for php, but this has some disadvantages.

1- No matter what size I set, it would still be too small. 2- If I set the memory size to "infinite", I could risk killing my server.

Ideally, I would like to “check” before I call json_decode (...) that the string will run out of memory.

Is it possible?

+4
source share
3 answers

JSON, . 1 , ( , MySQL ).

include , 9 . file_get_contents(), 1 , . PHP 1: 9 strlen() ( var_export()).

json_encode(), . (PHP , , JSON, .) JSON 670 .

JSON file_get_contents , 0,75 . json_decode() , 7 . 1:10 JSON-data-bytesize, PHP- RAM.

JSON , - :

if (strlen($my_json) * 10 > ($my_mb_memory * 1024 * 1024)) {
    die ('Decoding this would exhaust the server memory. Sorry!');
}

... $my_json - JSON, $my_mb_memory - , . ( , , intval(ini_get('memory_limit')), .)

, . , , :

    • 1-60000, PHP 1 , 10,5 12,5 ( ) 1:12-,
    1. 1 12000 , 5 ; 1: 5.
  1. 1 , , 7 , 1: 7.

, . , , ( , ) , json_decode().

, memory_get_usage() / memory_get_peak_usage() , .

+6

- . , , , ?

, , . , , explode() preg_split(), .

, API ; , , , JSON-.

(, ), , . ( .) , , . , . - .

+1
0

All Articles