如何转储字符串文件并将其另存为 HTML 文档


How to dump a string file and save it as a HTML document?

我有一个看起来像这样的脚本。

$html = <<<__END__
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
</head>
{$body}
</body>
</html>
__END__;

将此脚本输出另存为 HTML 文件的正确方法是什么。

例如。

我希望能够像这样。

save_to_html($html,'目录/文件名)'

当我转到目录时,我将能够找到包含上述变量内容的 html 文件。

看看file_put_contents(),以便使用

include('your_file.php');
file_put_contents('directory/filename',$html);
function save_to_html($html, $path)
{
    $f = fopen($path, 'w');
    if (file_put_contents($path, $html) === false)
    {
        return false;
    }
    return true;
}

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

使用示例:

save_to_html($html, 'directory/newfile.html');

将缓冲区与 ob_start 一起使用 & ob_get_contents

见 http://php.net/manual/fr/function.ob-get-contents.php

ob_start();
echo $html =' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
</head>
{$body}
</body>
</html>';
    $file_name='cache.txt';
if($fopen=@fopen(PATH.$file_name, 'a')){
         fwrite($fopen, ob_get_contents());
     fclose($fopen);
}
ob_end_flush();
ob_flush();
flush();

使用 echo 将内容放入缓冲区中,ob_get_content s 从缓冲区获取内容。然后保存在文件中。