php - 将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>
解决方案
当您使用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;
}
?>
推荐阅读
- javascript - 如何在 node.js 中创建 Get 请求以按日期对请求求和(可能是月、日或年)?
- javascript - 有没有办法获取 AJAX 响应的 responseType?
- dask - Dask ValueError:架构不同
- r - 来自数据帧的图形/矩阵(按条件)
- javascript - 为什么 indexOf 在搜索到的数组中找不到数组?(需要解释而不是解决方案)
- r - 在 ShinyR 中选择后如何重置表单?
- c# - 如何在 Windows 窗体中保存对象的状态
- ionic-framework - 如何在离子框架中直接导航到主页而不是 index.html?
- tensorflow - 在 mAP 不稳定的情况下,我应该何时停止目标检测模型训练?
- javascript - 将 setInterval 设置为多次调用,但在本机反应中只调用一次