要在 PHP 中保存文件,您可以使用 fopen()
和 fwrite()
函数,也可以使用 file_put_contents()
函数。
下面是一个使用 file_put_contents()
函数来保存字符串到文件中的例子:
<?php
$file = "example.txt";
$text = "Hello, world.";
// 打开文件并写入文本
file_put_contents($file, $text);
?>
要保存数组或对象,需要使用 serialize()
函数将它们序列化为字符串,然后保存该字符串。
<?php
$file = "example.txt";
$data = array("name" => "John Doe", "age" => 30);
// 序列化数组并写入文件
file_put_contents($file, serialize($data));
?>
您也可以使用 fopen()
和 fwrite()
函数写入文件,如下所示:
<?php
$file = "example.txt";
$text = "Hello, world.";
// 打开文件
$handle = fopen($file, "w");
// 写入文本
fwrite($handle, $text);
// 关闭文件
fclose($handle);
?>