![](/img/trans.png)
[英]How to load content from a .txt file with html in it … into a div using php or javascript
[英]How to Edit txt file content using php?
我想在txt文件中存儲用戶對我網站的評論。 所以...我想知道如何使用PHP編輯txt文件內容。
我的txt文件內容是這樣的......
uid=5
comment="Hello world"
time="2013:11:21:xx:xx"
uid=6
comment="Test comment"
time="2013:11:21:xx:xx"
所以..如果我想編輯uid = 5的評論,我怎么能用php做。 或者告訴我一個更好的方法,內容應該放在文本文件中以使這個任務變得狡猾。
我不想使用數據庫來存儲我的評論。 請幫助我解決這個問題。 Thansk
$txt_file = file_get_contents('path/to/file');
$rows = explode("\n", $txt_file); //you get all rows here
foreach ($rows as $row => &$data) {
if (strstr($data, 'uid=5') !== FALSE) {
//it means the following line contains your comment,
//work with it as string
$rows[$row + 1] = "comment=" . $newComment;
}
$data = $data . "\n";
}
file_put_contents('path/to/file', $rows);
json提供了一種將數組序列化為字符串的簡單方法。
使用json_decode和json_encode,您可以將上面的示例轉換為每行有一個json記錄。
然后使用上面的答案一次讀一行並查找你想到的uid。 只需json_decode該行即可獲得整個數組的注釋。
此方法允許您稍后更改注釋中的屬性數量和/或使某些屬性可選,而不會使文件解析復雜,或依賴雙空白鏈接或空白技巧來分隔記錄。
文件示例
{ 'uid':'5','comment'='Hello world','time'='2013:11:21:xx:xx' }\r\n
{ 'uid':'6','comment'='Hello world','time'='2013:11:21:xx:xx' }\r\n
如果您沒有可用的數據庫服務器,我建議您使用SQLite 。 它就像一個真正的數據庫服務器,但它將數據存儲在磁盤上的文件中。 通過使用常規文本文件,您遲早會遇到麻煩。
我同意Bhavik Shah,如果你不能使用數據庫,那么csv將更容易使用。 然而,假設你不能做下面的任何一個是一個解決方案,不是最優雅,但一個解決方案。
$file = 'myfile.txt';
$fileArray = file( $file );
$reachedUser = false;
for( $i=0; $i<=count($fileArray); $i++ ){
if( preg_match('/uid=6/', $fileArray[$i] ) == 1 ){
$reachedUser = true;
continue;
}
if( $reachedUser && preg_match('/comment=/', $fileArray[$i]) ){
$fileArray[$i] = "comment=\"This is the users new comment\"\n";
break;
}
}
reset( $fileArray );
$fh = fopen( $file, "w" );
foreach( $fileArray as $line ){
fwrite( $fh, $line );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.