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;
?>

因此,在之前的 HTML 页面中,他们输入了 2 个值,即他们的姓名和位置,然后上面的 php 代码将获取他们输入的信息并将其存储在 userswhobought.txt

这是它目前的存储方式:

Username=John
Location=UK
commit=
===============

但我只是希望它像这样存储

John:UK
===============
Nextuser:USA
==============
Lee:Ukraine

所以我更容易提取。

谢谢

4

6 回答 6

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;
?>
于 2013-03-12T01:29:47.930 回答
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;
?>
于 2013-03-12T01:29:51.677 回答
0
foreach($_POST as $variable => $value) {
    $write_this = "$variable:$value\r\n"
    fwrite($handle, $write_this );
}
fwrite($handle, "===============\r\n");

此外,我建议将 header() 调用移到退出之前。从技术上讲,这是可行的,但这不是大多数人所做的。

于 2013-03-12T01:30:17.870 回答
0

而不是你的 foreach,只需添加$_POST['Username'].":".$_POST['Location']."\r\n"你的文件。

于 2013-03-12T01:31:23.907 回答
0

只需放置fwrite($handle, "===============\r\n");在您的循环内。

于 2013-03-12T01:35:23.527 回答
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 选项中也是。

于 2013-03-12T01:36:26.053 回答