从表单获取用户输入,使用PHP将其写入文本文件

4
作为订阅者获取的一部分,我想使用php从html表单中抓取用户输入数据,并将其写入制表符分隔的文本文件中。所写数据需要用制表符分隔并附加在其他数据下面。
在表单上点击“订阅”后,我希望它删除表单并在div中显示一个小消息,如“感谢订阅”。
这将在WordPress博客上,并包含在弹出窗口中。
以下是具体细节。非常感谢您的任何帮助。
变量/输入如下:
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];

$leader是一个带有“是”和“否”选项的双选单选按钮。

$country是一个下拉菜单,其中包含40多个国家。

所有其他值都是文本输入。

我已经完成了所有基本的表单代码,除了操作,我真正需要知道的是:

如何使用php写入制表符分隔的文本文件,并在提交后用感谢消息替换表单?

再次感谢您的所有帮助。

6个回答

10
// the name of the file you're writing to
$myFile = "data.txt";

// opens the file for appending (file must already exist)
$fh = fopen($myFile, 'a');

// Makes a CSV list of your post data
$comma_delmited_list = implode(",", $_POST) . "\n";

// Write to the file
fwrite($fh, $comma_delmited_list);

// You're done
fclose($fh);

将implode中的逗号替换为\t,以实现制表符。


3

以追加模式打开文件

$fp = fopen('./myfile.dat', "a+");

将所有数据放在那里,使用制表符分隔。在末尾使用换行符。
fwrite($fp, $variable1."\t".$variable2."\t".$variable3."\r\n");

关闭你的文件

fclose($fp);

0

非常简单: 表单数据将被收集并存储在$var中 $var中的数据将被写入filename.txt \n将添加一个新行。 文件追加不允许覆盖文件

<?php
$var = $_POST['fieldname'];
file_put_contents("filename.txt", $var . "\n", FILE_APPEND);
exit();
?>

0
// format the data
$data = $Fname . "\t" . $email . "\t" . $leader ."\t" . $industry . "\t" . $country . "\t" . $zip;

// write the data to the file
file_put_contents('/path/to/your/file.txt', $data, FILE_APPEND);

// send the user to the new page
header("Location: http://path/to/your/thankyou/page.html");
exit();

通过使用header()函数重定向浏览器,您可以避免用户重新加载页面并重新提交数据的问题。

0

这是使用fwrite()的最佳示例,您最多只能使用3个参数,但通过添加“.”,您可以使用尽可能多的变量。

if isset($_POST['submit']){
    $Fname = $_POST["Fname"];
    $email = $_POST["emailPopin"];
    $leader = $_POST["radiobuttonTeamLeader"];
    $industry = $_POST["industry"];
    $country = $_POST["country"];
    $zip = $_POST["zip"];

    $openFile = fopen("myfile.ext",'a');
        $data = "\t"."{$Fname}";
        $data .= "\t"."{$email}";
        $data .= "\t"."{$leader}";
        $data .= "\t"."{$industry}";
        $data .= "\t"."{$country}";
        $data .= "\t"."{$zip}";

    fwrite($openFile,$data);
    fclose($openFile);
}

0

更换表单相对容易。确保将表单的操作设置为同一页。只需在“if(!isset($ _POST ['Fname']))”条件中包装表单。将您想要在表单发布后显示的任何内容放置在“else {}”部分内。因此,如果表单已发布,则将显示“else”子句中的内容;如果表单未发布,则将显示“if(!isset($ _POST ['Fname']))”的内容,即表单本身。您不需要另一个文件来使其工作。
要将POST值写入文本文件,请按照其他人提到的任何方法进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接