douoyou3348 2013-04-03 12:42
浏览 67
已采纳

PHP优化使用file_put_contents函数

I'm querying the database and then storing returned data to XML file with file_put_contents(). I'm wondering which way of invoking this function is better. Note that $data is large array and variable $rss can contain a big string in this case.

At first I implemented something like this:

foreach($data as $item)
{
    $rss .= '<title>'.getTitle($item['id']).'</title>';
    $rss .= '<data>'.getData($item['id']).'</data>.';
    file_put_contents($this->fileRss, $rss);
    unset($rss);
}

And then I changed above to:

foreach($data as $item)
{
    $rss .= '<title>'.getTitle($item['id']).'</title>';
    $rss .= '<data>'.getData($item['id']).'</data>.';
}

file_put_contents($this->fileRss, $rss);

Which way is better? Making a big, big variable $rss and then saving it or saving quite small variable every time? I'm not sure but I think IO operations are slower than memory operations so first way is better. Only problem may be memory limit.

  • 写回答

1条回答 默认 最新

  • douqin7086 2013-04-03 12:59
    关注

    The first example is incorrect, unless you add FILE_APPEND to file_put_contents.

    file_put_contents($this->fileRss, $rss, FILE_APPEND);
    

    I would rather manually open the file before the loop, write each chunk of rss data inside the loop, and close the file after the loop.

    $file = fopen($this->fileRss, 'w');
    foreach($data as $item)
    {
        $rss = '';
        $rss .= '<title>'.getTitle($item['id']).'</title>';
        $rss .= '<data>'.getData($item['id']).'</data>.';
        fwrite($file, $rss);
    }
    fclose($file);
    

    This way you do not store all the rss entries in memory, and you avoid opening and closing the file in each iteration. I have also replaced the unset with $rss = ''; to avoid garbage collection inside the loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP