Page 1 of 1

how can I add text in the middle of a text file

Posted: Wed Aug 30, 2006 9:30 am
by abzu
I am relatively new to php and I am trying to figure out how I can use it to add a block of text to an existing text file. I dont want to append to the file. I want to add the text at some point in the middle of the file and I would like to be able to use a sring to determine where that block will go rather than using a single character separator. I am thinking I need to split the file into an array and locate my string within that array, then add my text block after it and put it all back together. Unfortunately I don't know how to write the code that will do this. Nor do I know if this is the best way to go about it.

Can anyone help with this please?

Posted: Wed Aug 30, 2006 2:19 pm
by Ambush Commander

Posted: Fri Sep 01, 2006 1:27 pm
by abzu
That helps a lot. I managed to get part of the way there with your suggestions. what I have so far allows me to pull the file contents and alter it how I want. Now I am unable to push the new content back into the file using any of the methods I learned from the links you provided. I tried file_put_content as well as trying to just use fopen and then writing to it. It appears that I am not even able to open the file or create as file_put_content is supposed to do if it doesn't already exist. My first thought was permissions but it appears that they are all set properly. here is what i have so far. I have removed and added various parts of this in an attempt to find out if the problem is in the code I have already written but to no avail. Any suggestions?

Code: Select all

<?php

$filename = 'file.txt';
$content = file_get_contents($filename);
$newstring = ' cool';


$newcon =  substr_replace($content , $newstring , -13 , -14);

file_put_content($filename , $newcon);

?>

Posted: Fri Sep 01, 2006 1:42 pm
by Ambush Commander
All typos aside (you're missing an "s"), if you're not using PHP 5, file_put_contents() won't exist. The manual page shows you how to do it in PHP 4, use that code.

Posted: Fri Sep 01, 2006 6:33 pm
by abzu
The typo was jist when I put it here. It wasn't in my actual code. But you were right, I'm apparently not on php 5. I added the function from the manual page and it works like a charm. Thank you very much.

Code: Select all

<?php

function file_put_contents($n,$d) {
  $f=@fopen($n,"w");
  if (!$f) {
   return false;
  } else {
   fwrite($f,$d);
   fclose($f);
   return true;
  }
}

$filename = 'file.txt';
$content = file_get_contents($filename);
$newstring = ' cool';

$newcon =  substr_replace($content , $newstring , -13 , -14);
echo $newcon;

file_put_contents($filename,$newcon);

?>