我在一个免费的PHP支持服务器上有这个脚本:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
它会创建文件lidn.txt
,但它是空的。
如何创建文件并在其中写入内容, 例如“猫追逐老鼠”这一行?
答案 0 :(得分:90)
您可以使用更高级别的功能,例如file_put_contents($filename, $content)
,这与连续调用fopen()
,fwrite()
和fclose()
以将数据写入文件相同。
答案 1 :(得分:58)
考虑fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
答案 2 :(得分:17)
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
答案 3 :(得分:7)
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
您使用fwrite()
答案 4 :(得分:6)
写文件很容易:
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
答案 5 :(得分:3)
我使用以下代码在我的网络目录上写文件。
<强> 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);
}
?>
这是一个有效的脚本。如果要在您的网站上使用,请务必更改表单操作中的网址和 fopen()功能中的目标文件。
祝你好运。答案 6 :(得分:3)
fwrite()
是一个更快的smidgen,file_put_contents()
只是这三种方法的包装,所以你会失去开销。
Article
file_put_contents(文件,数据,模式,上下文):
file_put_contents
将字符串写入文件。
此函数在访问文件时遵循这些规则。如果设置了FILE_USE_INCLUDE_PATH,请检查 filename 副本的包含路径 如果文件不存在,则创建该文件然后如果设置了LOCK_EX则打开文件并锁定文件,如果设置了FILE_APPEND,则移动到文件末尾。否则,清除文件内容 将数据写入文件并关闭文件并释放任何锁定。 此函数返回成功时写入文件的字符数,或失败时返回FALSE。
的fwrite(文件,字符串长度):
fwrite
写入打开的文件。该函数将在文件末尾或达到指定长度时停止,
以先到者为准。此函数返回写入的字节数或失败时的FALSE。
答案 7 :(得分:3)
要在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 );
答案 8 :(得分:1)
以下是步骤:
关闭文件
$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);