phpを使ってテキストファイルの先頭に上書きせずにテキストを挿入する方法
質問
私は持っている:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
ただし、ファイルの先頭が上書きされます。どうすれば挿入できるのでしょうか?
解決
質問の内容がよくわかりません。既存のファイルの先頭を上書きせずにデータを書き込みますか、それとも既存のファイルの先頭に新しいデータを書き込み、その後の既存のコンテンツを保持しますか?
ファイルの先頭を上書きせずにテキストを挿入するには, 追加するにはそれを開く必要があります (a+
それよりも r+
)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
ファイルの先頭に書き込もうとしている場合, 、ファイルの内容を読み取る必要があります (「 file_get_contents
) まず、新しい文字列に続いてファイルの内容を出力ファイルに書き込みます。
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
上記のアプローチは小さなファイルには機能しますが、大きなファイルを読み取ろうとするとメモリ制限に遭遇する可能性があります。 file_get_conents
. 。この場合、使用を検討してください rewind($file)
, 、ハンドルのファイル位置インジケーターをファイル ストリームの先頭に設定します。使用上の注意 rewind()
, でファイルを開かないようにします。 a
(または a+
) オプション:
ファイルを追加 (「a」または「a+」) モードで開いた場合、ファイルに書き込むデータは、ファイルの位置に関係なく、常に追加されます。
他のヒント
上書きせず、全体を変数/メモリにロードすることなく、ファイル ストリームの途中に挿入する実際の例:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
追加するためにファイルを開くのと同じ結果が得られます
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
ファイルの先頭にテキストを配置したい場合は、次のように最初にファイルの内容を読み取る必要があります。
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>
所属していません StackOverflow