如何在php变量中保存页面源?

i have an html email being generated by certain php functions and collected from several tables in the database and organized in an html layout..right now it is all in a preview.php page for testing the layout but when i need to send it to subscribers, i need to get the html code generated from this page only,and send that code in an email.and i mean by page source the one i see when i right click on the page and then click view source..so how do i get this page source ? or save it into a certain variable to use it ?

Option 1:

Use file_get_contents(), since it returns the file in a string:

$html = file_get_contents('preview.php')

Your whole html is now saved in the $html variable as a string.

Option 2:

If your preview.php contains some PHP processing, you can do this instead (so that the PHP codes get executed, and you still get the resulting html):

ob_end_clean();
ob_start();
include('preview.php');
$html = ob_get_contents();
ob_end_clean();

Again, your whole html is now saved in the $html variable as a string.

What you want looks a bit weird to me (why not get it into a variable instead of echoing it?)
Anyway, have a look to the ob_start & ob_get_contents functions

You should generate your html with PHP and then save it in a session variable before echoing it.

Something like

$html = <<<HTML
<html>
<-- Here you have the full html of the page -->
</html>
HTML;
session_start();
$_SESSION['html'] = $html;
echo $html;

Then when you want to send the email you simply do

$message = $_SESSION['html'];

The right way is to have preview.php do this:

$html = '';
$html .= '<div>';
$html .= 'Text within div';
$html .= '</div>';
// etc
echo $html;
// Do other stuff with $html

But if you just want the lazy way, leaving preview.php doing echo statements, do this:

ob_start();
// Make the HTML using echo
$html = ob_get_contents();
ob_end_clean();