Generating JSON "Allowed memory size of..."

Hello,

I use this code to generate a json output from a content.

<?php

header('Content-type: application/json; charset=utf-8');
$today = date('Y-m-d');
$data = $pages->find('veranstaltungen')->children()->visible()->filterBy('article_push', '1')->filterBy('date_event_start', '>', $today)->limit(3);
$json = [];
foreach($data as $article):
    
    $image = $article->event_image()->toFile();
    $thumbURL = $image? $image->resize(1200)->url(): '';
    $imageURL = $image? $image->url(): '';

     $event_date_end = "";
        if($article->date_event_end()->isNotEmpty())
        {
           $event_date_end = date("d.m.Y",strtotime($article->date_event_end()));
        }


    $json[] = [

        'title' => (string)$article->title(),
        'event_date_start' => (string)date("d.m.Y",strtotime($article->date_event_start())),
        'event_date_end' => $event_date_end,
        'event_start_time' => (string)$article->start_time(),
        'event_end_time' => (string)$article->end_time(),
        'text' => (string)$article->text_full(),
        'thumb' => $thumbURL
        
    ];

endforeach;

echo json_encode($json);

?>

If the limit is greater than 3 I get the following error:

 PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) in /home/www/web404/html/kirby/vendor/getkirby/toolkit/vendors/abeautifulsite/SimpleImage.php on line 1101
[Mon Apr 23 16:50:56 2018] [error] [client 48.188.47.75] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 32768 bytes) in /home/www/web404/html/kirby/vendor/filp/whoops/src/Whoops/Util/Misc.php on line 1

Is my code so bad ?

I suspect your images are huge in file size (as in megabytes, not dimensions) and its running out of ram trying to resize them. I would address that first. You can also raise the memory limit in your PHP ini file, provided your server has enough ram.

As a side note, I would recommend using something like the Image Shrink plugin to scale them down on upload but you can still trip out the memory limit if you source image is huge, but its a good way to handle clients uploading 5mb photos straight from a digital camera.

I wrote a blog post a couple of weeks ago on automating image optimisation, perhaps it’s useful.

Thank you @jimbobrjames

now I use Image Shrink

If it is correct if a thumbnail of a picture has already been generated, the same Thumnail is not created each time the function is called ?

Greetings Perry

That should be the case. In earlier versions of Kirby, all thumbnail were deleted if an image was deleted. That shouldn’t be the case anymore.

I’d still check memory limit settings in php.ini.