2013-03-12 96 views
0

我試圖以某種格式將數據存儲在文本文件中。以某種格式存儲變量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 

因此,我提取更容易。

感謝

+1

不要發明自己的序列化格式,考慮節省自己很多痛苦:使用現有的序列化格式,如xml,json,php的本地'serialize()',yaml等等。還要考慮數據庫:sqlite,mysql ,bdb ... – 2013-03-12 01:32:37

+0

我也推薦使用serialize()。另一件事我特別是當數據已經是XML格式時,是這樣的:file_put_contents($ this-> pathAndFileName,$ xml-> asXML()); – Muskie 2013-03-12 01:42:17

回答

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這樣的數據庫選項 - 你甚至可以在nosql選項中存儲數據,比如mongodb。

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

嗨,它沒有捕獲用戶用這個代碼輸入的數據 – 2013-03-12 01:40:50

+0

@JohnKee這沒有意義....什麼是表單字段的名稱? – Tushar 2013-03-12 01:48:44

+0

哎呀我的壞,修好了。謝謝 – 2013-03-12 01:51:33

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; 
?> 
0
foreach($_POST as $variable => $value) { 
    $write_this = "$variable:$value\r\n" 
    fwrite($handle, $write_this); 
} 
fwrite($handle, "===============\r\n"); 

此外,我建議移動頭()退出之前調用正確的。從技術上講,這是有效的,但這不是大多數人的做法。

0

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

0

只需將fwrite($handle, "===============\r\n");放置在循環中即可。