【发布时间】:2010-12-18 15:22:47
【问题描述】:
我在一台免费的 PHP 支持服务器上有这个脚本:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
它创建了文件lidn.txt,但它是空的。
如何创建一个文件并在其中写入一些内容, 比如“猫追老鼠”这句台词?
【问题讨论】:
我在一台免费的 PHP 支持服务器上有这个脚本:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
它创建了文件lidn.txt,但它是空的。
如何创建一个文件并在其中写入一些内容, 比如“猫追老鼠”这句台词?
【问题讨论】:
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
【讨论】:
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
你使用fwrite()
【讨论】:
fclose($fh)),我尝试使用$fh = fopen('lidn.txt', 'w+');,` $fh = fopen('lidn.txt', 'a+'); ` 但他们都没有工作
写文件很容易:
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
【讨论】:
【讨论】:
file_put_contents() 仅适用于 PHP5。在这种情况下似乎不是问题(毕竟你的答案得到了接受),但可能仍然有一些主机运行 PHP4.x。
put_file_contents() 最初是在 PHP5 中引入的,此后也包含在以后的版本中。
我使用以下代码在我的 web 目录中写入文件。
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
这是一个工作脚本。如果您想在您的网站上使用它,请务必更改表单操作中的 url 和 fopen() 函数中的目标文件。
【讨论】:
fwrite() 速度快了一点,file_put_contents() 只是这三种方法的包装,所以你会失去开销。
Article
file_put_contents(文件、数据、模式、上下文):
file_put_contents 将字符串写入文件。
此函数在访问文件时遵循这些规则。如果设置了 FILE_USE_INCLUDE_PATH,请检查 filename 副本的包含路径 如果文件不存在则创建文件,如果设置了 LOCK_EX,则打开文件并锁定文件,如果设置了 FILE_APPEND,则移至文件末尾。否则,清除文件内容 将数据写入文件并关闭文件并释放所有锁。 该函数成功返回写入文件的字符编号,失败返回FALSE。
fwrite(文件,字符串,长度):
fwrite 写入一个打开的文件。函数将在文件末尾或达到指定长度时停止,
以先到者为准。此函数返回写入的字节数或失败时返回 FALSE。
【讨论】:
要写入PHP 中的文件,您需要执行以下步骤:
打开文件
写入文件
关闭文件
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "a");
fwrite($file , $select->__toString());
fclose($file );
【讨论】:
步骤如下:
关闭文件
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
【讨论】: