簡體   English   中英

使用php,如何插入文本而不覆蓋文本文件的開頭

[英]Using php, how to insert text without overwriting to the beginning of a text file

我有:

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

可以在這里找到它的Composer lib

如果要將文本放在文件的開頭,則必須首先讀取文件內容,如:

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

?>

你可以打開文件進行追加

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM