Php 를 사용하여,어떻게 덮어쓰지 않고 텍스트 삽입해 시작 부분의 텍스트 파일

StackOverflow https://stackoverflow.com/questions/103593

  •  01-07-2019
  •  | 
  •  

문제

나이:

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

작곡가 lib 을 위해 그것은 여기에서 찾을 수 있습니다

당신 같은 파일을 열 추가

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

?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top