【问题标题】:How to insert text into a .txt file using form inputs?如何使用表单输入将文本插入 .txt 文件?
【发布时间】:2013-01-02 01:26:30
【问题描述】:

我想要一个页面,我可以在其中将文本输入到输入表单中,然后将该文本插入到文本文件中的适当位置。

例如,输入表单将有 2 个输入表单域: 1. 多少比萨饼? 2. 哪个城市?

它会更新一个文本文件,上面写着:

(2) 中有 (1) 个比萨饼。

纽约有 5 个披萨

很简单,但是我该怎么做呢?

【问题讨论】:

  • 为什么是文本文件?数据库不是更好的主意吗?
  • 因为我只需要它来做一件非常简单的事情
  • 在谷歌中输入php文件不是很简单吗? ?? ?? 3 秒,你去goo.gl/w7Yyj

标签: php


【解决方案1】:

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>

【讨论】:

  • 如何访问文本?我把php放到script.php中,创建了html页面,但是提交的时候,什么都没有发生。
  • 您应该在服务器上有 file.txt。如果它不存在,那么您应该检查目录的写权限。
【解决方案2】:

使用 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 );

}

【讨论】:

  • 这是 php 还是 javascript?我对编码一无所知。我正在寻找可以从字面上复制粘贴的代码。
  • 它是 PHP。现在,您不会通过复制和粘贴学到很多东西,是吗?但如果你愿意,你可以这样做。只需将 $savePath 值更改为您要保存文本文件的任何位置。
猜你喜欢
  • 2020-05-08
  • 2018-11-08
  • 2013-11-14
  • 1970-01-01
  • 2016-05-15
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多