This is a discussion on how to delete last line of file within the PHP Language forums, part of the PHP Programming Forums category; Kenneth wrote: [snip] Without knowing the size of your file, or how it otherwise is accessed, the generic advice would ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Kenneth wrote:
[snip] Without knowing the size of your file, or how it otherwise is accessed, the generic advice would be to avoid using file() or looping through the whole file with fgets(). And to work on a copy instead of a "live" version. Take a look (again) at the link, which R. Rajesh Jeba Anbiah gave you. The idea is thant you search backwards and look for some marker (which may or may not be a newline, as it is not required for the xml-document to be valid). Once positioned at the right spot in the file, you can start overwriting with new data, perhaps truncating the file first. A quick and dirty way to your specific problem, could be something like... $end_string = "</member>\n"; $length_end_string = strlen($end_string); $fh = fopen('employees.txt','r+'); fseek($fh, -$length_end_string, SEEK_END); fwrite($fh, "some string that needs to be added"); fwrite($fh, $end_string); fclose($fh); It is of course required that any script modifying the file, all write the same string in the end. /Bent |
|
|||
|
Ken Robinson wrote:
> Kenneth wrote: > No Ken, you were missing and end bracket. Anyway here is what I have so far. It is working now but I think it takes too much resources. Let me know if you can improve the following code somehow. ----------------------------------------------------------------------------------------- //Search for the file $key = "</members>"; //load file into $fc array $fc=file("members.xml"); //open same file and use "w" to clear file $f=fopen("members.xml","w"); //loop through array using foreach foreach($fc as $line) { if (!strstr($line,$key)) //look for $key in each line fputs($f,$line); //place $line back in file } fclose($f); ------------------------------------------------------------------------------------------------- The problem is that I have to file() which I heard takes up to much resources, but it works. Can I replace the code somehow? >>Ken Robinson wrote: >> >>>Kenneth wrote: >> >>Ken, I tried your code. Everything fits logically but i keep getting > > >>following error message; >>Parse error: syntax error, unexpected ')', expecting ';' in >>c:\Inetpub\wwwroot\final\test\lastline.php on line 13 > > > I (obviously) had a few typo's in the code I posted. It should read: > <? > $inp = file('yourfile.name'); > $out = fopen('yourfile.name','w'); > for ($i=0;$i<count($inp)-1;$i++) > fwrite($out,$inp[$i]); > fclose($out); > ?> > > You should always take any code posted with a grain of salt and don't > just copy it verbatim. Always check for errors in both the syntax and > logic. > > Ken > |