Search code examples
phpstringechofputs

Can echo be manipulated to write to a file in PHP


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.


Solution

  • 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();.