php - How to append text to a file a 15 lines above its end -


I am trying to add the HTML to a file using fwrite () . My final goal is to add 15 lines from the end of the file. Even I have so far:

  & lt ;? Php $ file = fopen ("index.html", "r +"); // Explore Search ($ file, SEEK_END, 0); // Get that location and save $ filesize = ftell ($ file); // Find the length of the file length ($ file, SEEK_SET, $ filesize + 15); // Write your data $ main = & lt; & Lt; & Lt; MAIN // html here comes MAIN; FILIT ($ file, $ main); // File handler fclose off ($ file); ? & Gt;   

It just keeps overwriting at the top of the file. Thank you.

The sample code in the question is not based on the lines, because the size of the file you are working with (Unless there is any notion about the definition of lines in the application which is not mentioned here). If you want to work with lines, you will need to search for new line letters (which separates the next line).

If the target file is not a large file (so we can load the whole file in memory), we use PHP's underlying file () to use all the rows in a file You can read in the array, and then insert the data after the 15th element. Something like this:

  & lt ;? Php $ lines = file ($ filename); $ Num_lines = Counting ($ rows); If ($ num_lines & gt; 15) {array_splice ($ rows, numerals, numeric values ​​- 15, 0, array ($ content)); File_put_contents ($ filename, implode ('', $ rows)); } Other {file_put_contents ($ filename, PHP_EOL. $ Content, FILE_APPEND); }    

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -