PHP File: Inserting Lines into a File



PHP Array Tips - Part 14: Like removing line from file, with little trick in array, we can insert lines into file. Just read into array, insert element to array, then write back to file.
<?php
$f = "test.txt";

// read into array
$arr = file($f);

// add second line
array_splice($arr,1,0, array("test line 2\r\n"));

// reindex array
$arr = array_values($arr);

// write back to file
file_put_contents($f,implode($arr));
?>


Series this article:
PHP File: 3 Way of Reading File
PHP File: Reading File at Particular Lines
PHP File: Reading File at Particular Byte Ranges
PHP File: Checking File or Directory
PHP File: Showing All File in A Directory
PHP File: Showing All Files and Folders in Particular Directory
PHP File: Retrieving File Statistic
PHP File: Retrieving More File Information
PHP File: Counting Lines in a File
PHP File: Counting Characters and Words in File
PHP File: Writing File
PHP File: Locking and Unlocking File
PHP File: Removing Lines From File
PHP File: Inserting Lines into a File


Tag: file, insert line Category: PHP Basic Post : April 14th 2008 Read: 2,569 Bookmark and Share

blog comments powered by Disqus