PHP没有生成内容

时间:2017-03-21 07:57:00

标签: php html generator

我想用PHP创建一个简单的HTML文件生成器,其中用户输入一些数据,而.php文件生成带有HTML代码的输出,包括来自用户的数据。

问题是我的生成器只生成一个空白.html文件。

表单很简单:

<form action="html_form_submit.php" method="post">
<textarea name="name" rows="2" cols="20"> </textarea>
<input type="submit" value="Submit"/></form>

html_form_submit.php文件:

<?php
    ob_start();
    $name = @$_POST['name'];
?>
<html><body>
Name: <?php echo $name; ?><br>
</body></html>

<?php
    $output = ob_get_contents(); 
    $filename = 'test.html';
    !$handle = fopen($filename, 'w');
    fwrite($handle, $output);
    fclose($handle);
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Length: ". filesize("$filename").";");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/octet-stream; ");
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
    ob_end_clean(); 
?>

你知道吗,问题出在哪里?

2 个答案:

答案 0 :(得分:1)

试试这个

在html_form_submit.php文件中:

<?php
    ob_start();
if(isset($_POST['name'])){
    $name = $_POST['name'];
}
?>
<html><body>
Name: <?php echo $name; ?><br>
</body></html>

<?php
    $output = ob_get_contents(); 
    $filename = 'test.html';
    !$handle = fopen($filename, 'w');
    fwrite($handle, $output);
    fclose($handle);
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Length: ". filesize("$filename").";");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/octet-stream; ");
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
    ob_end_clean(); 
?>

答案 1 :(得分:1)

您应该在$output = ob_get_contents();之后立即调用ob_end_clean。 ob_end_clean清除缓冲区,使响应返回空。 试试这样:

<?php
    ob_start();
    $name = @$_POST['name'];
?>
    <html><body>
    Name: <?php echo $name; ?><br>
    </body></html>

<?php
    $output = ob_get_contents(); 
    ob_end_clean(); 
    $filename = 'test.html';
    !$handle = fopen($filename, 'w');
    fwrite($handle, $output);
    fclose($handle);
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Length: ". filesize("$filename").";");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/octet-stream; ");
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
相关问题