【问题标题】:Increment value in one text file and write text to another增加一个文本文件中的值并将文本写入另一个文件
【发布时间】:2017-07-07 03:37:47
【问题描述】:

我有一个包含表单的 HTML 脚本,该表单将 Name 值提交给 PHP 脚本。在这个 PHP 脚本中,我打开两个不同的文本文件,第一个文件是获取里面的数字,然后将其递增 1。另一个文件是打开,然后将新增加的数字连同 Post 中的 Name 值一起写入。 第一个文件里面只有一个数字,从“0”开始,这就是我遇到问题的地方。运行代码时,没有任何反应,表单完美提交,并调用了 PHP 脚本。但是两个不同文本文件中的唯一值都是“0”。相反,它应该在“amount.txt”文件中有“1”,在“textContent.txt”文件中应该有“要出现的文本:1 其他文本:名称”。

我不完全确定我错在哪里,对我来说这在理论上似乎是正确的。

下面是 PHP 部分,它是不工作的部分。

$nam = $_POST['Name'];

$pastAmount = (int)file_get_contents('/user/site/amount.txt');
$fileOpen1 = '/user/site/amount.txt';
$newAmount = $pastAmount++;
file_put_contents($fileOpen1, $newAmount);

$fileOpen2 = '/user/site/textContent.txt';

$fileWrite2 = fopen($fileOpen2 , 'a');
$ordTxt = 'Text to appear:  ' + $newAmount + 'Other text: ' + $nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);

【问题讨论】:

  • 不是连接运算符'.'而不是“+”? --- $ordTxt = '要出现的文本:' + $newAmount + '其他文本:' + $nam;
  • @Khan 是的,我刚刚发现,我的错误。谢谢。

标签: php html text int fwrite


【解决方案1】:

代替:

$newAmount = $pastAmount++;

你应该使用:

$newAmount = $pastAmount + 1;

因为$pastAmount++会直接改变$pastAmount的值。

然后代替

$ordTxt = 'Text to appear:  ' + $newAmount + 'Other text: ' + $nam;

你应该使用:

$ordTxt = 'Text to appear:  '.$newAmount.' Other text: '.$nam;

因为在 PHP 中我们使用 .用于连接。

PHP 代码:

<?php
$nam = $_POST['Name'];


// Read the value in the file amount
$filename = "./amount.txt";
$file = fopen($filename, "r");
$pastAmount = fread($file, filesize($filename));
$newAmount = $pastAmount + 1;
echo "Past amount: ".$pastAmount."-----New amount:".$newAmount;
fclose($file);

// Write the value in the file amount
$file = fopen($filename, "w+");
fwrite($file, $newAmount);
fclose($file);


// Write your second file 
$fileOpen2 = './textContent.txt';
$fileWrite2 = fopen($fileOpen2 , 'w+  ');
$ordTxt = 'Text to appear:  '.$newAmount.' Other text: '.$nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);
?>

【讨论】:

  • 非常感谢您的回答,它现在正在按照我想要的方式工作。
【解决方案2】:

首先,代码中的错误:

  1. $newAmount = $pastAmount++; => 这将分配 $pastAmount 的值,然后增加不是您想要的值。
  2. $ordTxt = 'Text to appear: ' + $newAmount + 'Other text: ' + $nam; => PHP 中的连接是使用 . 而不是 +

正确代码:

$nam = $_POST['Name'];

$pastAmount = (int)file_get_contents('/user/site/amount.txt');
$fileOpen1 = '/user/site/amount.txt';
$newAmount = $pastAmount + 1;
// or
// $newAmount = ++$pastAmount;

file_put_contents($fileOpen1, $newAmount);

$fileOpen2 = '/user/site/textContent.txt';

$fileWrite2 = fopen($fileOpen2 , 'a');
$ordTxt = 'Text to appear:  ' . $newAmount . 'Other text: ' . $nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 2016-08-14
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2011-07-24
    相关资源
    最近更新 更多