function permGen($handle, $a,$b,$c,$d,$e,$f,$g) {
foreach ($a as $key1 => $value1){
foreach($b as $key2 => $value2){
foreach($c as $key3 => $value3) {
fwrite(
$handle,
trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
);
}
}
}
}
// To write to a file
$handle = fopen('new.txt', 'w+');
permGen($handle, $other, $arguments, ...);
fclose($handle);
// To write to normal output (browser, whatever)
$handle = fopen('php://output', 'w');
permGen($handle, $other, $arguments, ...);
fclose($handle);
EDIT
If you don't want to modify your function in any way, then you can use output buffering to capture the printed output:
ob_start();
permGen($arguments...);
$output = ob_get_contents();
ob_end_clean();
file_put_contents(
'new.txt',
$output,
FILE_APPEND
);