您可以通过三种不同方式将现有文件复制到新文件 -
- 在循环中从一个中读取一行并写入另一个
- 将整个内容读到字符串并将字符串写入另一个文件
- 使用 PHP 的内置函数库包括 copy() 函数。
方法 1
在第一种方法中,您可以从现有文件中读取每一行并写入新文件,直到现有文件到达文件末尾。
在下面的 PHP 脚本中,在循环中逐行读取已存在的文件 (hello.txt),并将每一行写入另一个文件 (new.txt)
假定 “hello.txt” 包含以下文本 -
Hello World
启科普在线教程
PHP 教程
启科普在线教程
PHP 教程
例
以下是创建现有文件副本的 PHP 代码 -
<?php
$file = fopen("hello.txt", "r");
$newfile = fopen("new.txt", "w");
while(! feof($file)) {
$str = fgets($file);
fputs($newfile, $str);
}
fclose($file);
fclose($newfile);
?>
新创建的 “new.txt” 文件应具有完全相同的内容。
方法 2
这里我们使用 PHP 库中两个内置函数 -
file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
): string|false
此函数将整个文件读取到字符串中。$filename 参数是一个字符串,其中包含要读取的文件的名称
另一个函数是 −
file_put_contents(
string $filename,
mixed $data,
int $flags = 0,
?resource $context = null
): int|false
该函数将 $data 的内容放在 $filename。它返回写入的字节数。
示例
在以下示例中,我们读取字符串 $data 的“hello.txt”的内容,并将其用作写入“test.txt”文件的参数。
<?php
$source = "hello.txt";
$target = "test.txt";
$data = file_get_contents($source);
file_put_contents($target, $data);
?>
方法 3
PHP 提供 copy() 函数,专门用于执行复制操作。
copy(string $from, string $to, ?resource $context = null): bool
$from 参数是包含现有文件的字符串。$to 参数也是一个字符串,其中包含要创建的新文件的名称。如果目标文件已存在,则将被覆盖。
复制操作将根据文件是否成功复制返回 true 或 false。
示例
让我们使用 copy() 函数将 “text.txt” 作为 “hello.txt” 文件的副本。
<?php
$source = "a.php";
$target = "a1.php";
if (!copy($source, $target)) {
echo "复制失败: $source...\n";
}
?>