簡體   English   中英

如何將HTML中的表單數據保存到txt文件中。

[英]How do I save form data in HTML to a txt file.

我的程序使用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>

這是它的外觀圖:

在此處輸入圖片說明

如何通過按“提交”按鈕來更新原始txt文件?

經過測試,可以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>

程序.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"]));
?>
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";
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM