dsfs64664 2012-12-10 15:10
浏览 29
已采纳

文件中的可变内容消失,循环不进入

I have the following code to read from a file, and write back to it after some computation.

    if(file_exists(CACHE_FILE_PATH)) {
        //read the cache and delete that line!
        $inp = array();
        $cache = fopen(CACHE_FILE_PATH, 'r');
        if($cache) {
            while(!feof($cache)) {
                $tmp = fgets($cache);
                //some logic with $tmp
                    $inp[] = $tmp;
            }

            fclose($cache);
        }

        var_dump($inp);

        $cache = fopen(CACHE_FILE_PATH, 'w');

        var_dump($inp);
        if($cache) {

            var_dump($inp);

            foreach ($inp as $val) {
                echo "
IN THE LOOP";
                fwrite($val."
");
            }

            fclose($cache);
        }   
    }

The output of the var_dumps is:

array(3) {
  [0]=>
  string(13) "bedupako|714
"
  [1]=>
  string(16) "newBedupako|624
"
  [2]=>
  string(19) "radioExtension|128
"
}
array(3) {
  [0]=>
  string(13) "bedupako|714
"
  [1]=>
  string(16) "newBedupako|624
"
  [2]=>
  string(19) "radioExtension|128
"
}
array(3) {
  [0]=>
  string(13) "bedupako|714
"
  [1]=>
  string(16) "newBedupako|624
"
  [2]=>
  string(19) "radioExtension|128
"
}

Even though its an array, it is not going in the loop and printing IN THE LOOP! Why?

  • 写回答

1条回答 默认 最新

  • dongtun3259 2012-12-10 15:20
    关注

    This part of your code:

    fwrite($val."
    ");
    

    Should be:

    fwrite($cache, $val); // the "
    " is only required if it was stripped off after fgets()
    

    The first argument to fwrite() must be a file descriptor opened with fopen().

    Of course, if you had turned on error_reporting(-1) and ini_set('display_errors', 'On') during development you would have spotted this immediately :)

    As suggested in the comments, you should try to simplify your code by using constructs like file() to read the whole file into an array of lines and then use join() and file_put_contents() to write the whole thing back.

    If you just want a cache of key/value pairs, you could look into something like this:

    // to read, assuming the cache file exists
    $cache = include CACHE_FILE_PATH;
    
    // write back cache
    file_put_contents(CACHE_FILE_PATH, '<?php return ' . var_export($cache, true) . ';');
    

    It reads and writes files containing data structures that PHP itself can read (a lot faster than you can).

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

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了