如何使用 php 编辑 txt 文件内容


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 进行操作。或者告诉我一个更好的方法,内容应该放在文本文件中以使此任务变得轻松。

我不喜欢使用DataBSE来存储我的评论。请,有人在这件事上帮助我。坦斯克

$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 );
}