简体   繁体   English

如何使用表单输入将文本插入.txt文件?

[英]How to insert text into a .txt file using form inputs?

I want a page where I can enter text into an input form, and then have that text inserted into a text file into the appropriate places. 我需要一个页面,可以在其中输入文本到输入表单,然后将该文本插入文本文件中的适当位置。

For example, the input form will have 2 input form fields: 1. how many pizzas? 例如,输入表单将具有2个输入表单字段:1.多少个披萨? 2. which city? 2.哪个城市?

It will update a text file that says: 它将更新一个文本文件,内容为:

There are (1) pizzas in (2) . (2)中(1)个比萨饼。

There are 5 pizzas in New York 纽约有5个披萨

Very simple, but how do I do this? 很简单,但是我该怎么做呢?

PHP: PHP:

<?php
file_put_contents('file.txt', 'There are ' . $_POST['pizzas'] . ' pizzas in ' . $_POST['city']);
?>

HTML: 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>

Use JSON. 使用JSON。 It will let you edit the data easily (and because it's cool). 它可以让您轻松地编辑数据(并且因为它很酷)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM