Home  >  Article  >  Backend Development  >  PHP Tutorial: How to Append File Contents Using PHP

PHP Tutorial: How to Append File Contents Using PHP

王林
王林Original
2023-08-31 19:33:122018browse

PHP Tutorial: How to Append File Contents Using PHP

When people create a website, data is usually stored in a database. However, sometimes we need to store data in a file so that it is easier for people to read or modify it later.

PHP comes with many functions for reading and writing data from files. We can also use some of them to append data to files. In this tutorial, you will learn two different ways to append data to a file using PHP.

Understanding file_put_contents() Function

The file_put_contents() function is one of the simplest ways to write data to a file using PHP. It accepts four different parameters to determine its behavior. The parameters are:

  • filename: The path to the file location where we want to write data.
  • data: Specify the data to be written to the file. It is usually a string, but you can also specify an array or stream resource. This function will automatically implode the contents of a one-dimensional array using implode() in order to write the data to a file.
  • flags: Control the behavior of file_put_contents(). You can set three different flags here, either individually or in combination with other flags. Different flags can be combined using the | operator.
  • context: Only useful if you provide additional data to PHP when you read or access content in the stream.

Append data to a PHP file using file_put_contents()

file_put_contents() The default behavior of the function is to overwrite the contents of the given file with any new data you supply. This is not advisable when you want to keep the old data and add some new data. In this case, you can use the FILE_APPEND flag to let PHP know that it should append the data to the end of what was originally present in the file.

In some special cases, you may be appending data to a file from multiple scripts at the same time. In these cases, it is recommended to use the

LOCK_EX flag to obtain an exclusive lock on the file. This helps prevent data corruption or some other unexpected behavior. When you use this flag, other scripts will wait for the current process to finish writing to the file before appending their own data.

This is an example where

file_put_contents() is used to append some text to an existing file.

<?php

// Original File: Canada is a country in North America. .... bi-national land border.

// File Contents After this Line: Canada is a country in North America. .... bi-national land border.  Canada's capital is Ottawa,
file_put_contents('canada.txt', " Canada's capital is Ottawa,",  FILE_APPEND | LOCK_EX);

// File Contents After this Line: Canada is a country in North America. .... bi-national land border.  Canada's capital is Ottawa, and its three largest metropolitan areas are Toronto, Montreal, and Vancouver.
file_put_contents('canada.txt', " and its three largest metropolitan areas are Toronto, Montreal, and Vancouver.",  FILE_APPEND | LOCK_EX);

?>

In the above example, we write some strings into a file called

canada.txt which contains information about Canada. Both strings are appended to the end of the file one after the other.

Remember that this function will create a file if it does not exist yet. However, it does not create a directory that does not exist. So it's probably a good idea to check if the file exists before starting to write to it.

Use

fwrite() to write data to a PHP file

Writing data to a PHP file using the

file_put_contents() function is similar to calling fopen(), fwrite() and fclose( in sequence ). This means that performing multiple writes to the same file can be inefficient since we are constantly opening and closing the file again and again.

One way to solve this problem is to call these functions yourself. Just call

fopen() at the beginning of the write operation. Afterwards, use the fwrite() function to write the contents to the file multiple times. Finally, you can simply call fclose() to close the file handle. Let us now discuss each step in detail.

fopen() The function accepts four different parameters that you can use to tell PHP how the file should be opened.

  • filename: The name of the file you want to open.
  • mode: The mode for opening the file can be specified with one or two characters. We want to open this file and add some text to it. To append, set the pattern using the characters a or a . This places the file pointer at the end of the file. PHP will also try to create the file if it does not exist. When you open a file using the a method, you can also read the file content.
  • use_include_path: Instructs PHP to also look for files in the specified include path. Default is false.
  • context: Only useful if you provide additional data to PHP when you read or access content in the stream.
Now that the file is open, we can add information to the file using the

fwrite() function. fwrite() requires three parameters:

  • resource: This is the resource handle we created previously using fopen().
  • string: Text to append to the file.
  • length: Optional, used to set the maximum number of bytes that should be written to the file.
After all writing operations are completed, you can close the file handle using the

fclose() function.

这里是一个示例,向您展示如何使用 fopen()fwrite()fclose() 将数据附加到文件。

<?php

//open the file
$square_file = fopen("squares.txt", "a+");

//write the squares from 1 to 10
for($i = 1; $i <= 10; $i++) {
    $square = $i*$i;
    $cube = $square*$i;
    $line = "Square of $i is: $square.\n";
    fwrite($square_file, $line);
}

//read the first line of the file and echo
fseek($square_file, 0);
echo fgets($square_file);

//close the file
fclose($square_file);

?>
square.txt的内容
Square of 1 is: 1.
Square of 2 is: 4.
Square of 3 is: 9.
Square of 4 is: 16.
Square of 5 is: 25.
Square of 6 is: 36.
Square of 7 is: 49.
Square of 8 is: 64.
Square of 9 is: 81.
Square of 10 is: 100.

在本例中,我们将数字 1 到 10 的平方写入名为 square.txt 的文件中。我们在 a+ 模式下使用 fopen() 函数打开它,这意味着我们还可以从文件中读取内容以及附加我们自己的内容。每次 for 循环迭代时,都会将包含 $i 及其平方的当前值的新行附加到我们的文件中。

有一些函数,例如 fread()fgets(),您可以使用它们来读取文件中写入的内容。但是,您通常需要使用 fseek() 将文件指针放置在所需位置以按预期读取数据。循环结束后,我们转到文件的开头并使用 fgets() 读取其第一行。

最后,我们通过调用函数 fclose() 关闭文件句柄。

最终想法

在本教程中,我们学习了使用 PHP 将数据附加到文件的两种不同方法。使用 file_put_contents() 函数可以更方便地将数据写入文件。但是,当您必须对一个文件执行多次写入操作时,使用 fwrite() 会更有效。使用 fopen() 打开文件来附加数据还可以让您选择通过将文件指针移动到所需位置来读取其内容。

The above is the detailed content of PHP Tutorial: How to Append File Contents Using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn