Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json_encode big array

Tags:

json

php

I am trying to use json_encode on a big array, and the result returns nothing (yes, I checked that it is utf-8). When I started to investigate this issue I found that the problem arise when a string becomes bigger than 65536.

So when my array is of size 1245, its string from json_encode has length of string(65493), but when I increase array by just one, the string becomes longer than 65536, json_encode fails to output any result.

I thought that the problem is because of memory limit, but when I checked my php.ini I see that it is -1.

Any idea what can be a problem?

Basically I am doing something like this:

$arr = array();
for($i =0; $i<9000; $i++){
    $arr[] = array(
        'name'  => 'test',
        'str'   => md5($i)
    );
}
echo '<pre>'.json_encode($arr).'</pre>';

P.S. sorry guys. I found the problem, thanks to a person with an unreprintable name :-) (thank your Lawrence). <pre> is the culprit... for some reason it does not print the string in my browser, but it is there.

Lawrence, if you want, you can just write it and I will accept it as correct. Because you were the reason that I came up with this.

like image 431
Salvador Dali Avatar asked Aug 26 '13 23:08

Salvador Dali


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is the difference between json_encode and json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.

What does json_encode return?

Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


1 Answers

Just to remove confusion about this question. The answer is already found and it is in the question.

There is nothing wrong with json_encode function. It works correctly for every output. There is no limitation there except of your memory and how much of it are you giving to your script.

The problem was with browser's implementation of <pre> tag. If you provide too big string to this tag it does not print anything. So the way out is to output answer without <pre> tag

like image 125
Salvador Dali Avatar answered Oct 14 '22 05:10

Salvador Dali