繁体   English   中英

如何使用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做。 或者告诉我一个更好的方法,内容应该放在文本文件中以使这个任务变得狡猾。

我不想使用数据库来存储我的评论。 请帮助我解决这个问题。 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_decodejson_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM