Hello all, I am working on a little PHP project, and what i would like to do, is not to "append" text to the end of a file, not to write text to the begginging of the file, and not to overwrite the file, but I want to:
insert text into an arbatrary line of a file, not erasing anything else, just pushing the rest down a line.
This must be possible without saving it all into an array and putting it back line by line and inserting the extra one where i want it. There must be a better way. Thanks.
Insert Text into Middle of Text File
Moderator: General Moderators
- Ambush Commander
- DevNet Master
- Posts: 3698
- Joined: Mon Oct 25, 2004 9:29 pm
- Location: New Jersey, US
I came up with a working solution using arrays. I did the inserting manually though. I didn't look into array functions all that much. Any way it works.
feyd | Please use
Code: Select all
$date = date("U");
$title = stripslashes($_POST['title']);
$author = stripslashes($_POST['author']);
$article = stripslashes($_POST['article']);
$list = stripslashes($_POST['list']);
$file = fopen($date , "a" );
fwrite($file, "1\n" . $title . "\n" . $author . "\n" . $article);
// ====array part====
$array=file($list);
$countc=count($array);
$times=0;
$fileb=fopen($list,"w");
while ( $times <= $countc ) {
fwrite($fileb, $array[$times]);
if ($times == 2) {
fwrite($fileb, $date . "\n" . $title . "\n" . $author . "\n\n");
}
$times++;
}feyd | Please use
Code: Select all
andCode: Select all
tags where approriate when posting code. Read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]