Jump to content

How do i amend a line in a delimited text file using php?


davocold

Recommended Posts

i have the text file text.txt containing the following:

john,male,36,libra

jane,female,28,cancer

stive,male,33,gemini

and so on

i am able to read each line and edit its contents

the edited line is assigned to a variable.

what i need is a function that will replace a specific line in the text file with the new variable

i tried using fopen, fwrite, fclose but it is deleting everything in the text file.

i have a loop that ammends each line and i would like to include a write function in it.

Thanks,

a) make sure you are not using 'a' or 'a+' with fopen, because fwriting will always append it to the end of the file, regardless of what you do

 

b) you need to use ftell to get the current location of each line as you fread or fget it

 

c) you need to use fseek to move the pointer to the relevant location in the file before fwriting the line.  You would find the beginning of the target line by the previous line's ftell result + the strlen of that previous line

 

d) make sure when fwriting you pad with whitespace the difference in line length or else remove any trailing existing stuff. IOW if what you are changing is shorter than what was there before, you're gonna see that extra stuff still there.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.