将当前页面保存为HTML到服务器

时间:2010-09-23 03:26:07

标签: php html file save

有人建议将当前页面作为HTML文件保存到服务器的方法是什么?在这种情况下,还要注意安全性是一个问题。

我花了无数个小时寻找这个,并没有找到任何一件事。

非常感谢您的帮助,谢谢!

修改

谢谢大家的帮助,非常感谢。

6 个答案:

答案 0 :(得分:62)

如果您的意思是将页面输出保存在文件中,则可以使用缓冲来执行此操作。您需要使用的功能是ob_startob_get_contents

<?php
// Start the buffering //
ob_start();
?>
Your page content bla bla bla bla ...

<?php
echo '1';

// Get the content that is in the buffer and put it in your file //
file_put_contents('yourpage.html', ob_get_contents());
?>

这会将页面内容保存在文件yourpage.html中。

答案 1 :(得分:9)

我认为我们可以使用PHP的Output Control Functions,你可以先将内容保存到变量中,然后将它们保存到新文件中,下次你可以测试html文件是否存在,然后渲染否则重新生成页面。

<?php
$cacheFile = 'cache.html';

if ( (file_exists($cacheFile)) && ((fileatime($cacheFile) + 600) > time()) )
{
    $content = file_get_contents($cacheFile);
    echo $content;
} else
{
    ob_start();
    // write content
    echo '<h1>Hello world to cache</h1>';
    $content = ob_get_contents();
    ob_end_clean();
    file_put_contents($cacheFile,$content);
    echo $content;
}
?>

示例摘自:http://www.php.net/manual/en/function.ob-start.php#88212

答案 2 :(得分:3)

使用JavaScript将document.getElementsByTagName('html')[0].innerHTML作为隐藏输入值或通过ajax发送到服务器端。这比输出缓冲更有用,如果内容随后由JavaScript遍历/修改,服务器端可能没有任何概念。

答案 3 :(得分:3)

如果您希望在单个html文件中保存完整的html页面以及css,图像和脚本,您可以使用我编写的这个类:

  

这个类可以保存HTML页面,包括图像,CSS和   的JavaScript。

     

它获取给定页面的URL并检索它以存储在给定页面中   文件。

     

该类可以解析HTML并确定哪些图像,CSS和   它需要的JavaScript文件,因此也会下载这些文件   保存在保存到本地文件的HTML页面中。

     

可选择它可以跳过JavaScript代码,只保留页面   内容,并压缩结果页面删除空格。

http://www.phpclasses.org/package/8305-PHP-Save-HTML-pages-complete-with-images-CSS-and-JS.html

答案 4 :(得分:1)

我觉得你需要卷曲,这样你就可以保存任何页面的输出。使用curl与returntransfer true。并用输出做任何你想做的事。

答案 5 :(得分:1)

//function to use curl to get the content of the page.
//parameter used url and $data for the posting credentials to retrieve information.

function httpPost($url, $data){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

//
$filename="abc.html"; // whatever name you want.
$myfile = fopen($filename, "w") or die("Unable to open file!");
$txt =  httpPost(<url>, ""); //<url> replace by url you want.
fwrite($myfile, $txt);
fclose($myfile);
相关问题