php编写程序,创建文件并写入内容:(1)以覆盖模式写入若干行内容(2)以追加方式写入若干行内容粘贴代码及写入后文件内容
时间: 2023-06-21 13:06:02 浏览: 52
以下是以覆盖模式写入若干行内容的 PHP 代码:
```php
$file = "example.txt";
$content = "Hello World!\nThis is a test file.\n";
// 打开文件,以覆盖模式写入内容
$handle = fopen($file, "w");
fwrite($handle, $content);
fclose($handle);
// 读取文件内容并输出
echo file_get_contents($file);
```
以上代码会创建一个名为 `example.txt` 的文件,并将 `Hello World!` 和 `This is a test file.` 两行文字写入该文件。运行代码后,文件内容为:
```
Hello World!
This is a test file.
```
以下是以追加方式写入若干行内容的 PHP 代码:
```php
$file = "example.txt";
$content = "This is a new line.\nAnother new line.\n";
// 打开文件,以追加方式写入内容
$handle = fopen($file, "a");
fwrite($handle, $content);
fclose($handle);
// 读取文件内容并输出
echo file_get_contents($file);
```
以上代码会在 `example.txt` 文件的末尾追加两行文字:`This is a new line.` 和 `Another new line.`。运行代码后,文件内容为:
```
Hello World!
This is a test file.
This is a new line.
Another new line.
```