如何使用fopen和fwrite来读取,替换和添加文本文件?

At first, I have a program which can read and add something on a text file. Now, what I want to do is to select all the data from database table and open, copy and replace and add something on the text file. It was just like I select all (ctrl+a) the content of the text file and then paste it but with added something.

$fileArray = file($filename);
//acl 10-0146-506_lp arp 00:15:af:a5:68:b1
$findthis = "#endofpart1
";
$myKey = array_search($findthis,$fileArray);
array_splice($fileArray,$myKey,0,"acl ".$sn."_".$dd." arp ".$ma."
");
//http_access allow 09-0651-410_cp
$findthis2 = "#endofpart2
";
$myKey2 = array_search($findthis2,$fileArray);
array_splice($fileArray,$myKey2,0,"http_access allow ".$sn."_".$dd."
");


$fp = fopen($filename,'w');

foreach($fileArray as $value) {
    fwrite($fp,$value);
}

fclose($fp);

This code was the first program I did.