我正在尝试以特定格式将数据存储在文本文件中。
以下是代码:
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>
所以在之前的HTML页面上,他们输入了2个值,它们的名称和位置,然后上面的php代码会告诉我他们输入的信息,并将它存储在userswhobought.txt中
这就是它目前的存储方式:
Username=John
Location=UK
commit=
===============
但我只想让它像这样存储
John:UK
===============
Nextuser:USA
==============
Lee:Ukraine
所以我更容易提取。
由于
答案 0 :(得分:0)
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
fwrite($handle, $_POST['Username']);
fwrite($handle, ":");
fwrite($handle, $_POST['Location']);
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>
答案 1 :(得分:0)
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, ":");
fwrite($handle, $value);
fwrite($handle, "===============\r\n");
}
fclose($handle);
exit;
?>
答案 2 :(得分:0)
foreach($_POST as $variable => $value) {
$write_this = "$variable:$value\r\n"
fwrite($handle, $write_this );
}
fwrite($handle, "===============\r\n");
另外,我建议在退出之前将header()调用移到右边。从技术上讲,这是有效的,但并不是大多数人所做的。
答案 3 :(得分:0)
只需在您的文件中添加$_POST['Username'].":".$_POST['Location']."\r\n"
,而不是您的foreach。
答案 4 :(得分:0)
只需将fwrite($handle, "===============\r\n");
放入循环中即可。
答案 5 :(得分:0)
拿原始代码
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>
并改为
<?php
$datastring = $_POST['Username'].":".$_POST['Location']."
===============\r\n";
file_put_contents("userswhobought.txt",$datastring,FILE_APPEND);
header ('Location: http://myshoppingsite.com/ ');
exit;
?>
您需要直接操作POST数据,而不是循环遍历$_POST
数据,然后您可以随意使用它,但我建议您查看mysql,postgres或sqlite等数据库选项 - 您可以甚至将数据存储在像mongodb这样的nosql选项中。