PHP appending to file from specific position

好久不见. 提交于 2019-12-20 02:34:41

问题


In php i am opening a text file and appending to it. However I need to append 3 chars before the end of file. In other words i need to append/write from a specific place in the file.

Can any one help?

Best Regards Luben


回答1:


You need to open the file for edit, seek to the desired position and then write to the file, eg.:

<?php
  $file = fopen($filename, "c");
  fseek($file, -3, SEEK_END);
  fwrite($file, "whatever you want to write");
  fclose($file);
?>

Further reference at php.net - fseek doc

Hope that helps.




回答2:


If it's a short text file and you are only doing this once you can read in the contents (with fread()), store it only upto 3 chars from the end using substring and then append your new content onto the end of that and write.

But as I say if this is a regular thing and/or with large files, this isn't the best approach. I'll have a think.

Hope this helps



来源:https://stackoverflow.com/questions/5979274/php-appending-to-file-from-specific-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!