Log in

View Full Version : How to edit text file without using a helping file using PHP



SafeY
12-22-2012, 08:03 AM
hey , I need a function which can take values from text boxes and save every value to the text file in certain place .
I did this but I used an external text file , I took what I need from the original file then put the new values nect to them in the helping file and then I copied it content to my original file .

my file :

Sally = 10
Sami = 50

I want it to be like this :

Sally = 1230
Sami = 23450

here's my old code :


if(file_exists($trID_Log_File) && filesize($trID_Log_File) > 0) {
$h = fopen($trID_Log_File, "r");
$contents = fread($h, filesize($trID_Log_File));
fclose($h);
$out_h = fopen("output filename", "w");
if(!stristr($contents, "TrID is best suited to analyze binary files!")) {
$lines = explode("\n", $contents);
foreach($lines as $line) {
if(strlen($line) > 5) {
$line_arr=explode("=",$line);
if ($line_arr[0]=='Sally') {
$line_arr[1]="10"; // The New Value
}
fwrite($out_h, implode("=", $line_arr)."\n");
}
}
}
}

so I'm writing to "output.txt" and then coping it back to my file , How can I do that ?

jscheuer1
12-22-2012, 09:02 AM
That function looks like it's doing more than just writing to a file.

Anyways, when writing to a file you always have the option of either appending to it or of overwriting it. It sounds like you want to overwrite the existing file. And unless you're working with PHP < version 5, it's a lot easier to do these sorts of things with:

file_ get_ contents - gets the contents of the file as a string

and:

file_ put_ contents - writes a string variable to the file, optionally appending or overwriting.

There's also just:

file

If you want to get the contents of the file as an array.

See:

http://php.net/manual/en/function.file.php

traq
12-22-2012, 09:24 PM
why are you checking this, exactly?

if(!stristr($contents, "TrID is best suited to analyze binary files!"))

and why do you assume there in an = in the string just because there's more than 5 characters?

if(strlen($line) > 5) {
$line_arr=explode("=",$line);

And do you want to deal only with "Sally"? Or might you have other name=>value pairs also? How many?

Do you need to validate the names (i.e., allow only certain names, or allow any name submitted)?

Do you need to validate the numbers, or just save them?

Do you have to keep the name = number format, or are you willing to use something else that might be simpler?