fwrite()
函数本身不能创建新文件,但它可以在一个已存在的文件上写入内容
<?php
$filename = "example.txt";
$content = "Hello, this is a sample text!";
// 检查文件是否存在,不存在则创建新文件
if (!file_exists($filename)) {
touch($filename);
}
// 使用 fwrite() 在文件中写入内容
$result = fwrite($filename, $content);
if ($result === false) {
echo "Error writing to file.";
} else {
echo "Successfully wrote to file.";
}
?>
在这个示例中,我们首先检查文件是否存在,如果不存在,我们使用 touch()
函数创建一个新文件。然后,我们使用 fwrite()
函数将内容写入文件。