Friday, May 6, 2011

File rewrite not working?

test.php

<?php
$filec = fopen('test.txt','w');

$arr = file('test.txt');

foreach ($arr as $key => $value) {
    fwrite($filec,$value);
}

fclose($filec);
?>

test.txt

asdjlaksjd
asdhfwejkyhtjkre
jfdhgdjkf'hgjldsff
sfjnkbnm,cv
sm,nxcm,b,
sdjlhfskld
jfsdfwerwlur
slfdjsdkljfklsdjf

When I run test.php, test.txt is emptied. Does anyone know why?

Echoing $value, etc seems to work.

From stackoverflow
  • When you call fopen with w, you are effectively clearing the file. When you call file, you're reading from that cleared file.

    Put the file call before the fopen one.

    a2h : Oh wow, how did I not notice that? Thanks.

0 comments:

Post a Comment