Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing php script output to file [closed]

Tags:

Is there a native function or set of functions in PHP that will allow me to echo and print php file output into file.

For example code will generate HTML DOM that needs to be put into .html file and then displayed as static page.

like image 248
Chris Hermut Avatar asked Apr 25 '13 21:04

Chris Hermut


People also ask

How do I print a PHP script?

The echo command is used in PHP to print any value to the HTML document. Use <script> tag inside echo command to print to the console.

Where does PHP output go?

If it is turned on then stdout output will still go to the standard output of the console/browser but php://output will go to the buffer until the buffer reaches it's capacity or you manually flush the buffer.

How files can be opened for input and output in PHP?

Open a file using fopen() function. Get the file's length using filesize() function. Read the file's content using fread() function. Close the file with fclose() function.


2 Answers

The easiest method would be to create a string of your HTML data and use the file_put_contents() function.

$htmlStr = '<div>Foobar</div>';
file_put_contents($fileName, $htmlStr);

To create this string, you'll want to capture all outputted data. For that you'll need to use the ob_start and ob_end_clean output control functions:

// Turn on output buffering
ob_start();
echo "<div>";
echo "Foobar";
echo "</div>";

//  Return the contents of the output buffer
$htmlStr = ob_get_contents();
// Clean (erase) the output buffer and turn off output buffering
ob_end_clean(); 
// Write final string to file
file_put_contents($fileName, $htmlStr);

Reference -

  • ob_start()
  • ob_get_contents()
  • ob_end_clean()
  • file_put_contents()

  • PHP output control documentation

like image 159
Lix Avatar answered Sep 21 '22 05:09

Lix


file_put_contents($filename, $data)

http://php.net/manual/en/function.file-put-contents.php

like image 28
Keshav Saharia Avatar answered Sep 22 '22 05:09

Keshav Saharia