我在一个免费的PHP支持服务器上有这个脚本:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
它创建文件lidn.txt,但它是空的.
如何创建文件并在其中写入内容,例如"Cats chase mice"行?
Sav*_*man 124
您可以使用更高级的功能就像file_put_contents($filename, $content)是相同的调用fopen(),fwrite()以及fclose()先后将数据写入一个文件.
sat*_*ish 76
考虑fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
Run Code Online (Sandbox Code Playgroud)
Pes*_*sse 21
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.fwrite.php
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
Run Code Online (Sandbox Code Playgroud)
你用 fwrite()
小智 9
写文件很容易:
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
Run Code Online (Sandbox Code Playgroud)
我使用以下代码在我的Web目录中写入文件。
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
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);
}
?>
Run Code Online (Sandbox Code Playgroud)
这是一个工作脚本。如果要在网站上使用它,请确保在表单操作中更改url,并在fopen()函数中更改目标文件。
祝好运。
小智 6
为了写入文件,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 );
Run Code Online (Sandbox Code Playgroud)fwrite()速度更快,而且file_put_contents()只是这三种方法的包装,因此您将损失开销。
文章
file_put_contents(文件,数据,模式,上下文):
将file_put_contents一个字符串写入文件。
这个函数如下访问文件。如果FILE_USE_INCLUDE_PATH时设置这些规则,检查包括路径的副本文件名 创建文件,如果它不存在,则打开文件,并锁定该文件,如果LOCK_EX位如果FILE_APPEND是一套,移到文件末尾。否则,清除文件内容。将数据写入文件,然后关闭文件并释放所有锁。该函数返回成功时写入文件的字符编号,失败则返回FALSE。
fwrite(文件,字符串,长度):
在fwrite一个开放的文件。该函数将停止在文件末尾或当它达到指定的长度,以先到者为准first.This函数返回失败写入的字节或FALSE的数量。
小智 5
步骤如下:
关闭档案
$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);
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
212003 次 |
| 最近记录: |