Azer Qurbanov Azer Qurbanov -4 years ago 97
PHP Question

Parse huge json data to html with PHP is slow

I have one problem with HUGE JSON DATA. I get json data from backend with service and then i parse the data into HTML with PHP. When i get raw JSON data it takes 2 second, but when I parse it into HTML, it takes too long about 35 seconds. How can i accelerate parse time? Thanks beforehands. Below is my code. I use recursive function and for loops inside that function.


$str='<ul style="padding: 0px;padding-left: 5px;list-style: none">';
for ($x=0;$x<count($allstructure);$x++){




return $str;
public function iterator($data)


for($i=0;$i<count($data);$i++) {



$str.='<li style="display:flex"><input type="checkbox" class="rehbersecim"></li>';


$str.='<li style="display:flex"><input type="checkbox" class="checkqutu" name="vezife[]" value="'.$data[$i]->listPosNames[$z]->posNameId.'"><p style="width:230px;height:20px"><b>'.$data[$i]->listPosNames[$z]->posName.'</b></p> '.$this->createHtml($data[$i]->listPosNames[$z]->posNameId).'</li>';







return $str;


Answer Source

Your biggest name problem in the code above is the use of for(...; count(...); ...). This forces PHP to do count() every time you go through the loop in question, and you have three of these. When dealing with large data, that will be murderously slow.

Instead of doing it that way, call count() one time for each loop, like so:

$structureCount = count($allstructure);
for ($x=0; $x<$structureCount; $x++){

    $str .= '<li>' . $allstructure[$x]->name . '</li>';
    $str .= '<li>' . $this->iterator($allstructure[$x]->child) . '</li>';


A good resource for this kind of thing is For this problem, it shows that calling count() each time through takes approximately 340% as long as calling it once, like I did above. Because you have 3 of these loops effectively nested, this one change means your app may be taking about 3.43 = 39 times as long as it should be.

Also, as TomTom101 pointed out in the comments, you probably don't want to show "HUGE" data to the user all at once. You should consider paging (i.e., showing only part of the data at one time).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download