Search code examples
phpfwrite

PHP - Trying to re-write a file and it's leaving blank spaces


Hello i have an issue when re-writting a file:

static function Remove($plate){

    $_parkedlist=parking::Read();
    $_remove = false;
    $_stillparkedlist = array();

    foreach($_parkedlist as $_car){

        if($_car[0] == $plate){

            $_firsttime = $_car[1];
            $_now = date('Y-m-d H:i:s');
            $_timelapse = strtotime($_now) - strtotime($_firsttime);


            $_topay = $_timelapse * 10;

            echo "$_topay <br>";

            $_remove = true;


        } else {

            $_stillparkedlist [] = $_car;

        }
    }

    if ($_remove == true){

        $mifile = fopen('parked.txt',"w");

        foreach($_stillparkedlist as $_car){    

            if($_car[0]!=""){

                    $_line = $_car[0]."=>".$_car[1]."\n";       
                    fwrite($mifile,$_line);
            }

        }

        fclose($mifile);
    }
}

The original file is like this:

234FSC=>2016-09-07 17:06:23
JAG823=>2016-09-07 17:06:15
706KHB=>2016-09-07 17:06:15
980GHB=>2016-09-07 17:06:15

The first time i remove it adds blank spaces (Removed 706KHB)

234FSC=>2016-09-07 17:06:23

JAG823=>2016-09-07 17:06:15

980GHB=>2016-09-07 17:06:15

If i remove again it starts showing "Notice: Undefined offset: 1 in ...\parking.php" and the file looks like this

234FSC=>2016-09-07 17:06:23

=>
JAG823=>2016-09-07 17:06:15

=>
980GHB=>2016-09-07 17:06:15

=>

I have tried all i could find but this is still happening even with the if($_car[0]!="") and isset($_car[0]!)

How can i re-write without this error?


Solution

  • I would assume that each line is read from the file with a newline already attached to it.

    So when you execute this line

    $_line = $_car[0]."=>".$_car[1]."\n"; 
    

    It is adding another newline so instead do

    $_line = $_car[0]."=>".$_car[1]; 
    

    So you are not adding another newline