The easiest way is to just make your whole shebang one big transaction. Of course, if one insert fails they all fail, but often that is what you want.
Just do this:
$toss=pg_exec($conn,"begin");
for ($i=0;$i<gajillions;$i++){
$query = "you make this part";
$res=pg_exec($conn,$query);
}
$toss=pg_exec($conn,"commit");
this makes a 10,000 row insert run in <1 second, instead of the usual 30 or more seconds with autocommit on each line.