inseting into text files with php

abzu

New Member
I haven't much experience with php and I am trying to use it to insert a chunk of text into the middle of a text file at a location determined by some kind of marker in the file. I am thinking that I will need to split the file into an array at the spot where I want to insert, add the desired code into the array and then put it all back together. Unfortuately I am not sure how to code this. Can anyone give some assistance, or better yet let me know of a simpler way to accomplsih this?
 

talk2frank

New Member
If by a marker in the file you mean a piece of text ie:

[INSERT HERE]

Use code like this:

$text='text to be inserted after marker';
$text="[INSERT HERE]\n".$text;
$new_file=str_replace('[INSERT HERE]',$text,implode('',file('filename.txt'));
$f=fopen('filename.txt','w');
fwrite($f,$new_file);
fclose($f);

This will leave the marker text (ie [INSERT HERE]) in the text file. If you want to remove the marker, simply remove line 2 of that code.
 
Top