0

我正在使用一小段代码通过 PHP 生成静态 html 页面。

这是代码:

<?php
ob_start();
file_put_contents('someName.html', ob_get_contents());
// end buffering and displaying page
ob_end_flush();

?>

上面的代码工作正常,它将创建 html 页面 (someName.html)。

我想要做的是将 html 的名称从“someName”.html 更改为 PHP 输出。PHP 页面是一个动态的 PHP 页面,它将根据用户通过 html 表单请求的内容显示一些结果。

例如:用户在输入框中输入 2,创建的 html 页面将是 2.html 而不是 someName.php。

我确实尝试过这样的事情,但没有奏效:

<?php
ob_start();
file_put_contents($usersInput'.html', ob_get_contents());
// end buffering and displaying page
ob_end_flush();

?>

有谁知道我需要怎么做?

编辑:

我现在已经尝试过这种方式:

<?php
if (isset($_POST['userInput']))    
{ 
file_put_contents($_POST['userInput'].'.html', ob_get_contents());

}
// end buffering and displaying page
ob_end_flush();

?>

所以基本上用户在 html 表单的输入字段中输入 2 并且 html 文件应该称为 2.html。

我得到这个错误:

Warning: file_put_contents(2.html) [function.file-put-contents]: failed to open stream: No such file or directory on line 1156.

这是在第 1156 行:

file_put_contents($_POST['userInput'].'.html', ob_get_contents());
4

1 回答 1

1

你有一个语法错误,你忘记了一个连接运算符:

file_put_contents($usersInput'.html', ob_get_contents());

file_put_contents($usersInput.'.html', ob_get_contents());
                             ^ -- here

编辑

对于您的failed to open stream错误,您可能应该使用绝对路径。处理文件时始终建议这样做。

如果要将文件放在与脚本运行的目录相同的目录中:

file_put_contents(__DIR__.'/'.$_POST['userInput'].'.html', ob_get_contents());

另请注意,用户可能输入的名称包含不会产生有效文件名的字符!

此外,您可能应该确保该目录是可写的:

is_writable(__DIR__);

检查有关魔术常量的文档,例如__DIR__

于 2013-08-23T12:13:43.837 回答