speerross Posted November 13, 2008 Share Posted November 13, 2008 I'm trying to add a string to the beggining of an xml file; I've tried the standard fopen, fwrite etc: $c=1; while ($c<=($filenum)) { $xmlfile1 = "splits/".$basefilename."-".$c.".xml"; $handler = @fopen($dir."/$xmlfile1","r+"); fwrite($handler,$batchid); fclose($handler); $c++; } This works, but as it adds the line it deletes text already in the file (which I need to preserve). What is the best method to solve this? Quote Link to comment https://forums.phpfreaks.com/topic/132532-adding-a-line-to-the-beggining-of-a-file/ Share on other sites More sharing options...
JonnoTheDev Posted November 13, 2008 Share Posted November 13, 2008 Read the file into a variable. Add your lines to another variable. Concatenate the two variables into a third variable. Write the third variable back to the file. Quote Link to comment https://forums.phpfreaks.com/topic/132532-adding-a-line-to-the-beggining-of-a-file/#findComment-689208 Share on other sites More sharing options...
trq Posted November 13, 2008 Share Posted November 13, 2008 <?php $file = file_get_contents('foo.txt'); $file = "new line of text\n" . $file; file_put_contents('foo.txt', $file); ?> Quote Link to comment https://forums.phpfreaks.com/topic/132532-adding-a-line-to-the-beggining-of-a-file/#findComment-689256 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.