[英]How to insert text into a .txt file using form inputs?
我需要一个页面,可以在其中输入文本到输入表单,然后将该文本插入文本文件中的适当位置。
例如,输入表单将具有2个输入表单字段:1.多少个披萨? 2.哪个城市?
它将更新一个文本文件,内容为:
(2)中有(1)个比萨饼。
纽约有5个披萨
很简单,但是我该怎么做呢?
PHP:
<?php
file_put_contents('file.txt', 'There are ' . $_POST['pizzas'] . ' pizzas in ' . $_POST['city']);
?>
HTML:
<form action="script.php" method="POST">
Pizzas: <input type="text" name="pizzas"><br />
City: <input type="text" name="city"><br />
<input type="submit" value="Save">
</form>
使用JSON。 它可以让您轻松地编辑数据(并且因为它很酷)。
if ( empty( $_POST['pizzaCount'] ) === false && empty( $_POST['city'] ) === false )
{
$savePath = 'folder/folder2/save.txt';
$content = array();
//does the file already exist?
if ( ( $fileContents = file_get_contents( $savePath ) ) !== false )
{
//get the old data
$content = json_decode( $fileContents , true );
}
//add the new data
$content[] = array( 'pizzaCount' => $_POST['pizzaCount'] , 'city' => $_POST['city'] );
//decode the new data
$content = json_encode( $content );
file_put_contents( $savePath , $content );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.