dounuogong0358 2011-08-10 01:12
浏览 61
已采纳

使用return语句时清除PHP文本文件

To start out with, I basically have a function that opens up a text file, grabs the first line, removes it from the file, and saves the file with the remainder. Everything is working fine except when I come to use the return statement to return the line retrieved. Using the return statement, for some reason it clears the file; removing the return statement, the function does what it's supposed to. I'm debating whether this is a PHP bug or if there's something hidden here that I'm not seeing. Parts of the code is listed below, any help will be immensely appreciated.

Thanks!

    $nlines = array();

    $lines  = file(CACHE_PATH."/test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $link  = $lines[0];

    $lcount = count($lines)-1;
    for($i=1; $i < $lcount; $i++)
    {
        $nlines[] = $lines[$i];
    }

    $file  = fopen(CACHE_PATH."/test.txt", 'w');

    for($i=0; $i <= $lcount; $i++)
    {
        fwrite($file, $nlines[$i]);
    }

    fclose($file);

    return $link;
  • 写回答

1条回答 默认 最新

  • doudichu1358 2011-08-10 01:18
    关注

    The code seems aright to me. However here is a simplified version. Its untested though:

    function something(){
    
        $lines  = file(CACHE_PATH."/test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $link  = $lines[0];
        unset($lines[0]);
    
        $file  = fopen(CACHE_PATH."/test.txt", 'w');
        fwrite($file, implode("
    " , $lines) );
        fclose($file);
    
        return $link;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭