davocold Posted November 11, 2009 Share Posted November 11, 2009 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, Quote Link to comment https://forums.phpfreaks.com/topic/181185-how-do-i-amend-a-line-in-a-delimited-text-file-using-php/ Share on other sites More sharing options...
.josh Posted November 12, 2009 Share Posted November 12, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/181185-how-do-i-amend-a-line-in-a-delimited-text-file-using-php/#findComment-955936 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.