首页 > 解决方案 > 将php表单输入写入txt文件

问题描述

我在下面有这个 php 表单,它在提交时返回(显示)一个简单的计算。我现在要做的是将两个输入(身高,体重)和结果(函数计算)提交到一个文本文件。但我也不希望显示文本文件的路径。理想情况下,我希望每次提交表单时都在文本文件中添加一个新行(由;分隔)。

<html>

<?php
function bmi($height, $weight) {
    $height = floatval($height);
    $weight = floatval($weight);
    return $weight / ($height * $height);
}
?>

<head>


    <title>Page Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<form action="" method="POST">
    <h4>BMI</h4>
    <input id="height" name="height" type="text" placeholder="height in meters or feet" value="<?php echo isset($_POST['height']) ? $_POST['height'] : ''; ?>" />
    <br/>
    <br/>
    <input id="weight" name="weight" type="text" placeholder="weight in kgs or lbs" value="<?php echo isset($_POST['weight']) ? $_POST['weight'] : ''; ?>" />
    <br/>
    <br/>
    <input class="submit" type="submit" value="Submit"/>
    <?php if (!empty($_POST['height']) && !empty($_POST['weight'])) : ?>

    <p id="result">Your score is <?php echo bmi($_POST['height'], $_POST['weight']); ?></p>
    <?php endif; ?>
</form>
</body>
</html>

标签: phphtmlforms

解决方案


当您使用fopen()模式时,您可以将行添加到同一文件中,您可以在听到a更多的 php fopen 模式

<?php
    function bmi($height, $weight) {
        $height = floatval($height);
        $weight = floatval($weight);
        $result = $weight / ($height * $height);
        $data_file = fopen("data_file.txt", "a") or die("Unable to open file!");
        $txt = $height.";".$weight.";".$result."\n";
        fwrite($data_file,$txt);
        fclose($data_file);
        return $result;
    }
    ?>

推荐阅读