PHP appending to file from specific position

后端 未结 2 929
借酒劲吻你
借酒劲吻你 2021-01-20 19:24

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

相关标签:
2条回答
  • 2021-01-20 19:48

    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

    0 讨论(0)
  • 2021-01-20 20:08

    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.

    0 讨论(0)
提交回复
热议问题