PHPを使ってテキストファイルへの書き出しと読み込み
- May 30th, 2015
たまに使う事があるのでメモ。
ファイルに書き出し
$path = $_SERVER['DOCUMENT_ROOT'].'/hoge/file.txt'; $handle = fopen($path, 'a+'); $str = "文字列1,文字列2\n"; fwrite($handle, $str); fclose($handle);
ファイルを読み込み
$path = $_SERVER['DOCUMENT_ROOT'].'/hoge/file.txt';
$handle = fopen($path, 'r');
$file = fread($handle, filesize($path));
fclose($handle);
$file = explode("\n", $file);
foreach ($file as $row) {
$cols = explode(',', $row);
echo trim($cols[0]).' : '.trim($cols[1]).'<br>';
}
/*
* 出力結果
* 文字列1 : 文字列2
*/- May 30th, 2015
