php 需要用PHP写在文件的开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1760525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:44:20  来源:igfitidea点击:

Need to write at beginning of file with PHP

phpfileappend

提问by Timothy

I'm making this program and I'm trying to find out how to write data to the beginning of a file rather than the end. "a"/append only writes to the end, how can I make it write to the beginning? Because "r+" does it but overwrites the previous data.

我正在制作这个程序,我试图找出如何将数据写入文件的开头而不是结尾。"a"/append 只写到最后,我怎样才能让它写到开头?因为“r+”会这样做,但会覆盖以前的数据。

$datab = fopen('database.txt', "r+");

Here is my whole file:

这是我的整个文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Facebook v0.1</title>
        <style type="text/css">
            #bod{
                margin:0 auto;
                width:800px;
                border:solid 2px black;
            }
        </style>
    </head>

    <body>
        <div id="bod">
            <?php
                $fname = $_REQUEST['fname'];
                $lname = $_REQUEST['lname'];
                $comment = $_REQUEST['comment'];
                $datab = $_REQUEST['datab'];
                $gfile = $_REQUEST['gfile'];

                print <<<form
                <table border="2" style="margin:0 auto;">
                    <td>
                        <form method="post"  action="">
                              First Name :
                              <input type ="text"
                                         name="fname"
                                         value="">
                              <br>

                              Last Name :
                                <input type ="text"
                                         name="lname"
                                         value="">
                              <br>

                              Comment :
                              <input type ="text"
                                         name="comment"
                                         value="">
                              <br>
                              <input type ="submit" value="Submit">
                        </form>
                    </td>
                </table>
                form;
                if((!empty($fname)) && (!empty($lname)) && (!empty($comment))){
                    $form = <<<come

                    <table border='2' width='300px' style="margin:0 auto;">
                        <tr>
                            <td>
                                <span style="color:blue; font-weight:bold;">
                                $fname $lname :
                                </span>

                                $comment
                            </td>
                        </tr>
                    </table>
                    come;

                    $datab = fopen('database.txt', "r+");
                    fputs($datab, $form);
                    fclose($datab);

                }else if((empty($fname)) && (empty($lname)) && (empty($comment))){
                    print" please input data";
                } // end table

                $datab = fopen('database.txt', "r");

                while (!feof($datab)){
                    $gfile = fgets($datab);
                    print "$gfile";
                }// end of while
            ?>
        </div>
    </body>
</html>

回答by Ben Regenspan

The quick and dirty:

又快又脏:

<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>

回答by Jordan Running

If you don't want to load the entire contents of the file into a variable, you can use PHP's Streamsfeature:

如果不想将文件的全部内容加载到变量中,可以使用 PHP 的Streams功能:

function prepend($string, $orig_filename) {
  $context = stream_context_create();
  $orig_file = fopen($orig_filename, 'r', 1, $context);

  $temp_filename = tempnam(sys_get_temp_dir(), 'php_prepend_');
  file_put_contents($temp_filename, $string);
  file_put_contents($temp_filename, $orig_file, FILE_APPEND);

  fclose($orig_file);
  unlink($orig_filename);
  rename($temp_filename, $orig_filename);
}

What this does is writes the string you want to prepend to a temporary file, then writes the contents of the original file to the end of the temporary file (using streams instead of copying the whole file into a variable), and finally removes the original file and renames the temporary file to replace it.

这样做是将您想要添加的字符串写入临时文件,然后将原始文件的内容写入临时文件的末尾(使用流而不是将整个文件复制到变量中),最后删除原始文件文件并重命名临时文件以替换它。

Note:This code was originally based on a now-defunct blog post by Chao Xu. The code has since diverged, but the original post can be viewed in the Wayback Machine.

注意:此代码最初基于 Chao Xu 的一篇现已失效的博客文章。此后代码出现了分歧,但可以在 Wayback Machine 中查看原始帖子。

回答by Kailash Badu

I think what you can do is first read the content of the file and hold it in a temporary variable, now insert the new data to the beginning of the file before also appending the content of the temporary variable.

我认为您可以做的是首先读取文件的内容并将其保存在一个临时变量中,现在将新数据插入到文件的开头,然后再附加临时变量的内容。

$file = file_get_contents($filename);
$content = 'Your Content' . $file;
file_put_contents($content);  

回答by Sergey Samoilenko

  1. Open a file in w+mode not a+mode.
  2. Get the length of text to add ($chunkLength)
  3. set a file cursor to the beginning of the file if needed
  4. read $chunkLengthbytes from the file
  5. return the cursor to the $chunkLength * $i;
  6. write $prepend
  7. set $prependa value from step 4
  8. do these steps, while EOF

    $handler = fopen('1.txt', 'w+');//1
    rewind($handler);//3
    $prepend = "I would like to add this text to the beginning of this file";
    $chunkLength = strlen($prepend);//2
    $i = 0;
    do{
        $readData = fread($handler, $chunkLength);//4
        fseek($handler, $i * $chunkLength);//5
        fwrite($handler, $prepend);//6
    
        $prepend = $readData;//7
        $i++;
    }while ($readData);//8
    
    fclose($handler);
    
  1. w+模式而非a+模式打开文件。
  2. 获取要添加的文本长度 ( $chunkLength)
  3. 如果需要,将文件光标设置到文件的开头
  4. $chunkLength从文件中读取字节
  5. 将光标返回到$chunkLength * $i;
  6. $prepend
  7. 设置$prepend第 4 步中的值
  8. 做这些步骤, while EOF

    $handler = fopen('1.txt', 'w+');//1
    rewind($handler);//3
    $prepend = "I would like to add this text to the beginning of this file";
    $chunkLength = strlen($prepend);//2
    $i = 0;
    do{
        $readData = fread($handler, $chunkLength);//4
        fseek($handler, $i * $chunkLength);//5
        fwrite($handler, $prepend);//6
    
        $prepend = $readData;//7
        $i++;
    }while ($readData);//8
    
    fclose($handler);
    

回答by Ajay Kumar

You can use the following code to append text at the beginning and end of the file.

您可以使用以下代码在文件的开头和结尾附加文本。

$myFile = "test.csv";<br>
$context = stream_context_create();<br>
  $fp = fopen($myFile, 'r', 1, $context);<br>
  $tmpname = md5("kumar");<br>

//this will append text at the beginning of the file<br><br>
  file_put_contents($tmpname, "kumar");<br>
  file_put_contents($tmpname, $fp, FILE_APPEND);<br>
  fclose($fp);<br>
  unlink($myFile);<br>
  rename($tmpname, $myFile);<br><br>
  //this will append text at the end of the file<br>
  file_put_contents($myFile, "ajay", FILE_APPEND);

回答by Kamil Szot

This code remembers data from the beginning of the file to protect them from being overwritten. Next it rewrites the all the data existing in file chunk by chunk.

此代码会记住文件开头的数据以防止它们被覆盖。接下来,它逐块重写文件中存在的所有数据。

$data = "new stuff to insert at the beggining of the file";
$buffer_size = 10000;

$f = fopen("database.txt", "r+");
$old_data_size = strlen($data);
$old_data = fread($f, $old_data_size);
while($old_data_size > 0) {
  fseek($f, SEEK_CUR, -$old_data_size);
  fwrite($f, $data);
  $data = $old_data;
  $old_data = fread($f, $buffer_size);
  $old_data_size = strlen($data);
}
fclose($f);

回答by yusuf

There is no way to write to the beginning of a file like you think. This is I guess due to reason how OS and HDD are seeing the file. It has got a fixed start and expanding end. If you want to add something in the middle or beggining it requires some sliding. If it is a small file just read it all and do your manipulation and write back. But if not, and if you are always adding to the beginning just reverse line order, consider the end as beginning...

无法像您想象的那样写入文件的开头。我猜这是由于操作系统和硬盘驱动器如何查看文件的原因。它有一个固定的开始和扩展的结束。如果你想在中间添加一些东西或开始它需要一些滑动。如果它是一个小文件,只需将其全部读取并进行操作并写回。但如果不是,并且如果您总是在开头添加相反的行序,请将结尾视为开头...

回答by RageZ

You can use fseekto change the pointer in the note.

您可以使用fseek更改笔记中的指针。

It has to be noted that if you use fwriteit will erase the current content. So basically you have to read the whole file, use fseek, write your new content, write the old data of the file.

需要注意的是,如果你使用fwrite它会清除当前的内容。所以基本上你必须读取整个文件,使用fseek,写入你的新内容,写入文件的旧数据。

$file_data = file_get_contents('database.txt')
$fp = fopen('database.txt', 'a');
fseek($fp,0);
fwrite($fp, 'new content');
fwrite($fp, $file_data);
fclose($fp);

If your file is really huge and you don't want to use too much memory, you might want to have two file approach like

如果您的文件真的很大并且您不想使用太多内存,则可能需要使用两种文件方法,例如

$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
    $contents .= fread($fp_source, 8192);
    fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');

The solution of Ben seems to be more straightforward in my honest opinion.

老实说,Ben 的解决方案似乎更直接。

One last point: I don't know what you are stocking in database.txtbut you might do the same more easily using a database server.

最后一点:我不知道你在储存什么,database.txt但你可以使用数据库服务器更容易地做同样的事情。

回答by Cyborg

One line:

一条线:

file_put_contents($file, $data."\r\n".file_get_contents($file));

Or:

或者:

file_put_contents($file, $data."\r\n --- SPLIT --- \r\n".file_get_contents($file));

回答by Arek - Krakiewicz.pl

file_get_contents()and file_put_contents()use more memory than using the fopen(), fwrite(), and fclose()functions:

file_get_contents()file_put_contents()使用更多的内存比使用fopen()fwrite()fclose()功能:

$fh = fopen($filename, 'a') or die("can't open file");
fwrite($fh, $fileNewContent);
fclose($fh);