2

I am writing a code for Sanskrit Natural Language Programming. Earlier the machine was on test mode, so I was testing and editing from an HTML frontend to my PHP code by sending variables via GET method.

Now the code has more or less become stable.

What I want now is to write the output to a predefined txt / HTML file instead of echoing it to the browser screen.

My typical code line looks as follow:

if ( $a === 1 ) // if a condition is satisfied.
{ 
    //Do something here
    echo "<p class = sa >X rule has applied. </p>\n";
}

Is there some method by which I can manipulate the echo function and use it as - fputs($outfile, $b); where $b is the string which is being echoed. In the present case :

fputs($outfile,"<p class = sa >X rule has applied. </p>\n");

The code is still in a bit of development phase. So, I dont think it is a good way to replace this echo with fputs with some regex. Otherwise for a single change - I will have to make changes in both versions of code - fputs and echo one.

What made me think this is - in Python I can redefine the python functions e.g. I can define a custom function max(a,b) even if it is a built in function. I don't know any way to make my 'echo' to do work of 'fputs' in PHP. In PHP parlance I want to do this in commandline. e.g.

if (isset($argv[0])){
 // Some function to replace echo with fputs for the whole program
}

Any pointers to this are welcome.

Dhaval Patel
  • 135
  • 1
  • 1
  • 8
  • Google found this rather quickly. http://codeutopia.net/blog/2007/10/03/how-to-easily-redirect-php-output-to-a-file/ – ElefantPhace Dec 30 '14 at 16:31
  • Incidentally, instead of testing `$argv`, you can check the `php_sapi_name()` function, or `PHP_SAPI` constant: http://php.net/manual/en/function.php-sapi-name.php – IMSoP Dec 30 '14 at 16:39

1 Answers1

4

You can use output buffering for this, because it lets you specify a callback function that can be used to transform the buffered data. Define a callback function which catches the buffered output and writes it to the file, while returning an empty string to the browser:

$outfile = fopen('log.txt', 'wb');
ob_start(function($x) use($outfile) {
    fwrite($outfile, $x);
    return '';
});

If you want to turn it off during the script so you can send output to the browser again, simply call ob_end_flush();.

Boann
  • 48,794
  • 16
  • 117
  • 146
  • Neat. I'd not seen `ob_start` with a callback before; I've expanded the description a bit so it's easier to understand without following the link. – IMSoP Dec 30 '14 at 16:37
  • You made my day. It serves my purpose. Good to learn output buffer. – Dhaval Patel Dec 30 '14 at 17:46