Showing posts with label fclose. Show all posts
Showing posts with label fclose. Show all posts

Monday, May 30, 2011

PHP Read text files

Reading files is just as easy as writing them.
<?php
$str = file_get_contents("myfile.txt");
echo $str;
?>
People might not like it, but it works and is super easy.

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);
?>