Jex’s Note

PHP 讀寫檔案

php讀寫檔

/home/user_me/test/t.txt :

line 1
line 2
line 3
line 4
line 5

讀:

$test = fopen('/home/user_me/test/t.txt', 'r');
while ( ! feof($test))
{
    echo fgets($test);
}
fclose($test);

feof — Tests for end-of-file on a file pointer

寫:

[1] 將第一行移除

$path = '/home/user_me/test/t.txt';
$contents = file_get_contents($path);
$rows = explode("\n", $contents);
array_shift($rows);
file_put_contents($path , join("\n", $rows));

join — Alias of implode()

[2] 新增到最後一行

$path = '/home/user_me/test/t.txt';
file_put_contents($path, md5(uniqid(rand(), TRUE)), FILE_APPEND);

[3] 控制整份檔案內容

$file_path = '/home/user_me/test/q.txt';
$fp = fopen($file_path, 'w');
$rows[] = 'line1';
$rows[] = 'line2';
$rows[] = 'line3';
fwrite($fp, join("\n", $rows));
fclose($fp);

fputs — Alias of fwrite()

寫 csv 檔:

$file_path = '/home/user_me/test/q.txt';
$fp = fopen($file_path, 'w');
fputcsv($fp, array('field 1', 'field 2', 'field 3'));
fputcsv($fp, array('1', '2', '3'));
fputcsv($fp, array('4', '5', '6'));
fputcsv($fp, array('7', '8', '9'));
fclose($fp);

Comments