挣扎!
以下代码应该从表单中获取值,将该值添加到从data.php读取的值,然后将新值重写为data.php
<?php
//get form value
$add_value = $_GET["txt_InterimDonationSubtotal"]; //Will always be a number (10.00, for example)
echo $add_value;
// get contents of a file into a string
$filename = "../assets/files/donation_total/data.php";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
//Say what you got!
echo $contents;
//Get the numbers outta there :) (Will be some kind of number '100.00' for example)
$value = substr($contents, 13);
$value_cleaned = substr($value, 0, -4);
//Add the two numbers together
$new_total = $value_cleaned + $add_value;
//Rewrite the values back to the file
$new_data_content = "<?php $$data=$new_total;?>";
file_put_contents('../assets/files/donation_total/data.php', $new_data_content);
?>
输出没有回应任何东西,因为它应该(只是现在,当我知道它正在工作时我将删除它),它确实将某些东西写回data.php,但不是什么这应该。以下是我在Sublime中打开它时在data.php中得到的内容:
<?php $=0;?>
正如您所看到的,变量'data'的名称未保存在文件中,并且不会将值一起添加!为什么呢?!
期望的输出是:
<?php $data='125.85';?>
感谢有人回答的帮助,我已经走到了这一步:
<?php
//get form value
$add_value = $_GET["txt_InterimDonationSubtotal"]; //Will always be a number (10.00, for example)
echo $add_value;
// get contents of a file into a string
$contents = file_get_contents('../assets/files/donation_total/data.php');
//Say what you got!
echo "contents:".$contents;
//Get the numbers outta there :) (Will be some kind of number '100.00' for example)
$value = substr($contents, 13);
$value_cleaned = substr($value, 0, -4);
//Add the two numbers together
$new_total = $value_cleaned + $add_value;
echo "newtotal:".$new_total;
//Rewrite the values back to the file
$new_data_content = "<?php $data='".$new_total."';?>";
file_put_contents('../assets/files/donation_total/data.php', $new_data_content);
?>
这现在命名变量就好了,但内容没有被读取和回显(为什么?!)并且值没有被加在一起,因为它没有很好地将文件内容与我一起使用猜猜。
答案 0 :(得分:0)
这是因为带双引号的字符串中的变量具有神奇的解释。当PHP看到字符串"<?php $$data=$new_total;?>"
时,它会说变量$data
和$new_total
在哪里,然后在字符串中计算这些变量。 $ new_total是一个已定义的变量,它的值写入字符串,但$ data不是,所以它的值不是。
然而,你可以使用像'<?php $$data=$new_total;?>'
这样的单引号来编写你的字符串。但是,所有文本都将按字面写入您的文件。
我认为你想要的是用字符串连接字符串。 '<?php $data="' . $new_total . '";?>'
您是否尝试过序列化?
<?php
$add_value = $_POST["txt_InterimDonationSubtotal"];
$contents = file_get_contents("../assets/files/donation_total/data.txt");
if($contents) {
$contents = unserialize($contents);
} else {
$contents = 0;
}
$contents += $add_value;
file_put_contents('../assets/files/donation_total/data.txt', serialize($contents));
?>