php写入文件如何写入换行
From PHP you are able to open up a file on your server and write to it. If the file does not exist we can create it, however, if the file already exists you must chmod it to 777 so it will be writable.
通过PHP,您可以在服务器上打开文件并对其进行写入。 如果该文件不存在,我们可以创建它,但是,如果该文件已经存在,则必须将其chmod设置为777,以便可写。
写入文件 ( Writing to a File )
When writing to a file, the first thing you need to do is to open up the file. We do that with this code:
写入文件时,您要做的第一件事是打开文件。 我们使用以下代码进行操作:
<?php
$File = "YourFile.txt";
$Handle = fopen($File, 'w');
?>
Now we can use the command to add data to our file. We would do this as shown below:
现在我们可以使用命令将数据添加到文件中。 我们将如下所示:
<?php
$File = "YourFile.txt";
$Handle = fopen($File, 'w');
$Data = "Jane Doe\n";
fwrite($Handle, $Data);
$Data = "Bilbo Jones\n";
fwrite($Handle, $Data);
print "Data Written";
fclose($Handle);
?>
At the end of the file, we use fclose to close the file we have been working with. You may also notice we are using \n at the end of our data strings. The \n servers as a line break, like hitting the enter or return key on your keyboard.
在文件的最后,我们使用FCLOSE关闭,我们一直在与该文件。 您可能还会注意到,我们在数据字符串的末尾使用\ n 。 \ n服务器是换行符,例如,敲击键盘上的Enter或Return键。
You now have a file called YourFile.txt that contains the data:Jane DoeBilbo Jones
现在您有了一个名为YourFile.txt的文件,其中包含以下数据:Jane DoeBilbo Jones
改写数据 ( Rewrite Data )
If we were to run this very same thing again only using different data, it would erase all of our current data, and replace it with the new data. Here is an example:
如果我们仅使用不同的数据再次运行同一件事,那么它将擦除所有当前数据,并用新数据替换它。 这是一个例子:
<?php
$File = "YourFile.txt";
$Handle = fopen($File, 'w');
$Data = "John Henry\n";
fwrite($Handle, $Data);
$Data = "Abigail Yearwood\n";
fwrite($Handle, $Data);
print "Data Written";
fclose($Handle);
?>
The file we created, YourFile.txt, now contains this data:John HenryAbigail Yearwood
我们创建的文件YourFile.txt现在包含以下数据:John HenryAbigail Yearwood
添加到数据 ( Adding To Data )
Let's say that we don't want to rewrite over all of our data. Instead, we just want to add more names to the end of our list. We would do that by changing our $Handle line. Currently, it is set to w which means write-only, beginning of the file. If we change this to a, it will append the file. This means it will write to the end of the file. Here is an example:
假设我们不想重写所有数据。 相反,我们只想在列表末尾添加更多名称。 我们可以通过更改$ Handle行来实现。 当前,将其设置为w ,表示文件的开始位置为只写。 如果将其更改为a,它将附加文件。 这意味着它将写入文件的末尾。 这是一个例子:
<?php
$File = "YourFile.txt";
$Handle = fopen($File, 'a');
$Data = "Jane Doe\n";
fwrite($Handle, $Data);
$Data = "Bilbo Jones\n";
fwrite($Handle, $Data);
print "Data Added";
fclose($Handle);
?>
This should add these two names to the end of the file, so our file now contains four names:John HenryAbigail YearwoodJane DoeBilbo Jones
这应该将这两个名称添加到文件末尾,因此我们的文件现在包含四个名称:John HenryAbigail YearwoodJane DoeBilbo Jones
翻译自: https://www.thoughtco.com/write-to-a-file-from-php-2693790
php写入文件如何写入换行