Page 1 of 1

writing to the same file recursively

Posted: Sat Apr 10, 2004 11:13 pm
by damithc
i have the following function.

Code: Select all

<?php
function adapt($tpl,$outfile, $mode='w'){
  ob_start(); 
  require $tpl; 
  $tplContents = ob_get_contents(); 
  ob_end_clean(); 
  $fp = fopen($outfile, $mode); 
  fputs($fp, $tplContents); 
  fclose($fp); 
}
?>
I use it (in command line mode) to read a php script (in the file given as $tpl), parse it and write the result to a file named $outfile. i can call it like given below.

Code: Select all

<?php
adapt('template1.php','testout.txt');
?>
contents of my template1.php file includes another call to the same adapt function, like given below.

Code: Select all

<?php
adapt('template2.php','testout.txt');
?>
since two calls involve different $tpl files, it does not end up in an infinite loop. I want both function calls to append to the same file. But they do not. Only the first call add to the file it seems. If the output files are different, they work as expected (i.e. two files will be created with expected output).

Can anybody suggest what i'm doing wrong :? ? If i'm not made my problem clear pls indicate :D

Posted: Sat Apr 10, 2004 11:29 pm
by Weirdan
you can try 'a+' mode instead of 'w'

Posted: Sun Apr 11, 2004 9:21 am
by damithc
Thanx for the reply :)
Tried 'a+'. did not work. I'm guessing the trouble is due to the file is being open (due to first call to adapt()) when 2nd call try to open it. can it be?

Posted: Mon Apr 12, 2004 8:06 am
by Weirdan
here is the small test suit I used:

Code: Select all

// file: func.php
function adapt($tpl,$outfile, $mode='a+'){
    ob_start();
    require $tpl;
    $tplContents = ob_get_contents();
    ob_end_clean();
    $fp = fopen($outfile, $mode);
    fputs($fp, $tplContents);
    fclose($fp);
}

// file: as.php
$global1 = "Global 1";
$global2 = "Global 2";
require_once 'func.php';
adapt('tst.php','tst');

// file: tst.php
global $global1;
echo $global1."\n";
require_once 'func.php';
adapt('tst2.php','tst');

//file: tst2.php
global $global2;
echo $global2."\n";

Code: Select all

weirdan@home$ php ./as.php

 weirdan@home$ cat tst
 Global 2
 Global 1
As you can see this test works exactly as it should. Give it a try in your environment.

Posted: Mon Apr 12, 2004 10:18 am
by damithc
Thanx a lot Weirdan. that works. apologies for not testing your earlier suggestion properly :oops: .

Now in 'tst.php', what if i want to print a message to the console, instead of sending it to the file 'tst'. all the 'echo's in tst.php are caught and written to tst (by adapt). But now and then i want to bypass this and print some debug info on the console.

I posted this question in another forum and you replied asking for some sample code :D

Posted: Tue Apr 13, 2004 2:25 pm
by Weirdan
ok, reply goes to that thread

Posted: Tue Apr 13, 2004 8:10 pm
by damithc
Reply posted here by Weirdan solves my problem. Thanx a lot. :D