首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用php,如何在不覆盖文本文件开头的情况下插入文本?

使用php,如何在不覆盖文本文件开头的情况下插入文本?
EN

Stack Overflow用户
提问于 2018-01-22 23:53:06
回答 2查看 0关注 0票数 0

有:

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

?>

但是它覆盖了文件的开头?

EN

回答 2

Stack Overflow用户

发布于 2018-01-23 08:38:26

插入文本而不重写文件的开头

$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);

如果你想写到文件的开头,您必须读取文件内容

$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
票数 0
EN

Stack Overflow用户

发布于 2018-01-23 09:32:27

工作示例:

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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档