如何将HTML格式的表单数据保存为txt文件。

时间:2015-07-01 09:37:07

标签: php html

我的程序使用PHP从名为“configurationSettings.txt”的txt文件中打开配置设置列表,并将数据从中放入表单。

我想弄清楚的是如果用户通过表单更改任何内容,我的程序如何使我的程序更新原始txt文件上的数据。

以下是txt文件数据的示例:

Channel 7
4.0000
6.0000

这是我的代码,它读取数据并填写我的表单:

<?php
$configFile = fopen("configurationSettings.txt", "r");
$title1 = fgets($configFile);
$gain1 = fgets($configFile);
$offset1 = fgets($configFile);
fclose($configFile);
?> 

<form action="program.php" method="post">
Channel 8 Title:<br>
<input type="text" name="channel0Title" value="<?php echo $title1 ?>">
<br>
Gain:<br>
<input type="text" name="channel0Gain" value="<?php echo $gain1 ?>">
<br>
Offset:<br>
<input type="text" name="Channel0Offset" value= "<?php echo $offset1 ?>">
<br>
<input type="submit" id ="submitButton" value="Submit">
</div>
</form>

这是一张它看起来像的照片:

enter image description here

如何通过按提交按钮来更新原始txt文件?

3 个答案:

答案 0 :(得分:7)

经过测试,100%工作。你不必创建.txt。如果不存在则自动创建。

的index.html

<form action="program.php" method="post">
    Channel 8 Title:<br><input type="text" name="channel0Title" value="Channel 7"><br>
    Gain:<br><input type="text" name="channel0Gain" value="4.000"><br>
    Offset:<br><input type="text" name="channel0Offset" value= "6.000"><br>
    <input type="submit" id ="submitButton" value="Submit">
</form>

program.php

<?php
    $title = $_POST["channel0Title"]; //You have to get the form data
    $gain = $_POST["channel0Gain"];
    $offset = $_POST["channel0Offset"];
    $file = fopen('configurationSettings.txt', 'w+'); //Open your .txt file
    ftruncate($file, 0); //Clear the file to 0bit
    $content = $title. PHP_EOL .$gain. PHP_EOL .$offset;
    fwrite($file , $content); //Now lets write it in there
    fclose($file ); //Finally close our .txt
    die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>

答案 1 :(得分:0)

它运作良好但是如果你的txt文件还没有存在你应该创建它,所以改变&#39; r&#39;用&#39; w +&#39;使您能够编写和读取txt文件,如果它不存在,则会创建一个新的txt文件

答案 2 :(得分:0)

if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
    die("There was an error writing this file");
}
else {
    echo "$ret bytes written to file";
}}