Milan
Milan

Reputation: 166

How to Edit txt file content using php?

i want to store users comments of my site, in a txt file. so.. i want to know how to edit txt file content using php.

my txt file contents goes like this...

uid=5
comment="Hello world"
time="2013:11:21:xx:xx"

uid=6
comment="Test comment"
time="2013:11:21:xx:xx"

so..if i want to edit uid=5's comment, how can i do it with php. or tell me a better method, content should go in text file to make this task eazy.

i dont like to use databse to store my comments. pls, someone help me in this matter. Thansk

Upvotes: 1

Views: 328

Answers (4)

Richard Poole
Richard Poole

Reputation: 591

I agree with Bhavik Shah, if you can't use a database then a csv would be easier to work with. However assuming you can't do either of those below is a solution, not the most elegant, but a solution none the less.

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

Upvotes: 0

Max Koretskyi
Max Koretskyi

Reputation: 105489

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

Upvotes: 2

xeo
xeo

Reputation: 832

json offers a simple way to serialize an array to a string.
using json_decode and json_encode you can convert your example above to have one json record per row.

then use the answer above to read one line at a time and look for the uid you have in mind. just json_decode the row to get entire array for the comment.

this method allows you to change the number of attributes on your comments later and/or make some of the attributes optional without making the file parsing complex, or relying on double blank links or white space tricks to separate records.

file example

{ '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

Upvotes: 1

morgoth84
morgoth84

Reputation: 1140

If you don't have a database server available, I suggest you use SQLite. It acts like a real database server, but it stores it's data in a file on disk. By using just a regular text file you're going to end up in trouble sooner or later.

Upvotes: 0

Related Questions