Monday, May 30, 2011

PHP Write to file

Writing to files with PHP is a snap, it's super easy, like most everything about PHP. First, open a file handle (or stream), write to the stream, then close it. ALWAYS CLOSE.
<?php
$fh = fopen("myfile.txt","w");
fwrite($fh,"hello world\n");
fclose($fh);
?>
When you write to the file, try to write only once if you can. If you need to store data, build it up then write it to file, like below.
<?php
$data = array("My data","hello","world","goes","here","write","to","file");
$str = "";
for($i=0;$i<sizeof($data);$i++)
{
    $str .= $data[$i]."\r\n";
}

$fh = fopen("myfile.txt","w");
fwrite($fh,$str);
fclose($fh);
?>

No comments:

Post a Comment