我尝试创建一个简单的PHP程序,它从输入字段写入文本并将其放在.txt文件中。我的代码出了什么问题?它不会在项目之间留出空格并复制前一项目并将其翻倍。该文件名为email.txt。这是代码:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$file = fopen("email.txt", "r+") or die("<h1>Eroarea 1</h1>"); //In caz ca fisierul nu este gasit
$s = fread($file, filesize("email.txt"));
$s = $name . "\n";
fputs($file, $s) or die("<h1>Eroarea 2</h1>"); //In caz ca server-ul nu poate fi contactat
fclose($file);
echo "<h1></h1>";
} ?>
<section id="five" class="wrapper style2 special fade">
<div class="container">
<header>
<h2>Writer</h2>
<p>Put text here</p>
</header>
<form method="post" action="#" class="container 50%" onSubmit="post">
<div class="row uniform 50%">
<div class="8u 12u$(xsmall)"><input type="text" name="name" placeholder="Email" /></div>
<div class="4u$ 12u$(xsmall)"><input type="submit" name="submit" value="Send" class="fit special" /></div>
</div>
</form>
</div>
</section>
答案 0 :(得分:0)
将内容附加到文件的更简单方法是使用file_put_contents():
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
file_put_contents('email.txt', $name . PHP_EOL, FILE_APPEND);
}
?>
如果文件不存在,那将创建该文件,如果存在则附加到该文件。