以某种格式存储变量PHP
我试图以某种格式将数据存储在文本文件中。以某种格式存储变量PHP
下面是代码:
<?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;
?>
于是他们把2值之前的HTML页面上,他们的名字和位置,然后上面的PHP代码会得到我自己的信息,他们输入什么,将其存储在userswhobought.txt
这是它如何存储的时刻:
Username=John
Location=UK
commit=
===============
但我只是希望它来存储这样
John:UK
===============
Nextuser:USA
==============
Lee:Ukraine
因此,我提取更容易。
感谢
把你原来的代码
<?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这样的数据库选项 - 你甚至可以在nosql选项中存储数据,比如mongodb。
<?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-12 01:40:50
@JohnKee这没有意义....什么是表单字段的名称? – Tushar 2013-03-12 01:48:44
哎呀我的坏,修好了。谢谢 – 2013-03-12 01:51:33
<?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;
?>
foreach($_POST as $variable => $value) {
$write_this = "$variable:$value\r\n"
fwrite($handle, $write_this);
}
fwrite($handle, "===============\r\n");
此外,我建议移动头()退出之前调用正确的。从技术上讲,这是有效的,但这不是大多数人的做法。
而不是您的foreach,只需在您的文件中添加$_POST['Username'].":".$_POST['Location']."\r\n"
。
只需将fwrite($handle, "===============\r\n");
放置在循环中即可。
不要发明自己的序列化格式,考虑节省自己很多痛苦:使用现有的序列化格式,如xml,json,php的本地'serialize()',yaml等等。还要考虑数据库:sqlite,mysql ,bdb ... – 2013-03-12 01:32:37
我也推荐使用serialize()。另一件事我特别是当数据已经是XML格式时,是这样的:file_put_contents($ this-> pathAndFileName,$ xml-> asXML()); – Muskie 2013-03-12 01:42:17