【问题标题】:How to clear memory on each execution?如何在每次执行时清除内存?
【发布时间】:2020-04-25 03:55:09
【问题描述】:

我有这样的事情:

<?php

ini_set('max_execution_time', 0);
ini_set('memory_limit', '1024M');

//require_once '../../tabkadeh/error_reporting.php';
function setName($name,$photoName, $new_file)
{
    var_dump($new_file);
    require_once 'files/lib/WideImage.php';
    require_once 'FarsiGD.php';

    $left = '+50';
    $top  = '+400';

    $bg = WideImage::load($photoName);
    //$final= $bg ->resize(400, 400);
    $final= $bg;
    $canvas = $final ->getCanvas();
    //$canvas->useFont('./Yekan.ttf', 200, $final->allocateColor(000, 000, 000));
    $new_name=(new FarsiGD)->persianText($name,'fa', 'normal');
    $canvas->useFont('./Ray-ExtraBlack.ttf', 40, $final->allocateColor(34, 84, 109));
    $canvas->writeText("left $left", "top $top",$new_name);
    $final->saveToFile($new_file);
}

$file = fopen("Main.txt", "r");
$i = 0;
$line_of_text = '';
while (!feof($file)) {
    $line_of_text .= fgets($file);
}
$myText = explode("\n", $line_of_text);
fclose($file);


$arrayCount = count($myText);
var_dump($myText);

for ($x = 0; $x < $arrayCount; $x++) {
    setName($myText[$x], './bgbg.jpg', './export/flower_stamp-'.$x.'.jpg');
}

此文件:Main.txt 包含大量数据(2000 行产品名称)。

我增加了内存限制;但是当我运行脚本时,这只适用于第 1 行到第 250 行或更少!
如何清理每一代照片的内存?

【问题讨论】:

  • 从文件中加载一行并进行处理。然后加载下一个!不要将所有内容都加载到大字符串中,然后将其组成一个数组,然后处理每个事件
  • 您还可以在完成变量后添加一些unset()。我并没有真正看到 2000 行产品名称,除非您同时连续运行同一脚本的多个实例,但这很可能会导致其他问题(因为所有实例都会写入同一个文件)
  • 谢谢@RiggsFolly;你能告诉我怎么做吗?我是前端开发人员,我不知道该怎么做!
  • 也许把所有数据都保存在数据库里会更好,
  • 基本上只需将代码移动到while (!feof($file)) { 循环中,这样每次加载一行时都调用setName()

标签: php memory memory-limit


【解决方案1】:

从文件中加载一行并处理它。然后加载下一个!不要将所有内容加载到 BIG STRING 中,然后将其制成一个数组,然后处理该数组的每次出现。

一旦你这样做了,你可能就不需要增加内存限制或执行时间了。

<?php

ini_set('max_execution_time', 0);
ini_set('memory_limit', '1024M');

//require_once '../../tabkadeh/error_reporting.php';
function setName($name,$photoName, $new_file)
{
    //var_dump($new_file);
    require_once 'files/lib/WideImage.php';
    require_once 'FarsiGD.php';

    $left = '+50';
    $top  = '+400';

    $bg = WideImage::load($photoName);
    //$final= $bg ->resize(400, 400);
    $final= $bg;
    $canvas = $final->getCanvas();
    //$canvas->useFont('./Yekan.ttf', 200, $final->allocateColor(000, 000, 000));
    $new_name = (new FarsiGD)->persianText($name,'fa', 'normal');
    $canvas->useFont('./Ray-ExtraBlack.ttf', 40, $final->allocateColor(34, 84, 109));
    $canvas->writeText("left $left", "top $top",$new_name);
    $final->saveToFile($new_file);
}

$file = fopen("Main.txt", "r");
$i = 0;
$line_of_text = '';
while ($line = fgets($file, 4096) !== false) {
    setName(trim($line), './bgbg.jpg', './export/flower_stamp-'.$i.'.jpg');
    $i++;
}

fclose($file);

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 2010-12-31
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多