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,

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.