Home >Backend Development >PHP Tutorial >Questions about ob_start.

Questions about ob_start.

WBOY
WBOYOriginal
2016-07-06 13:53:241045browse

ob_start is described in the manual:

This function will turn on output buffering. When output buffering is activated, the script will not output content (except http headers), instead the content to be output is stored in an internal buffer.

So this is what I understand:

<code><?php
    ob_start();
    echo 'ob_start'; // 按理说ob_start不应该输出啊。但是确实输出了。</code>

Why is it different from what is described in the manual?

Reply content:

ob_start is described in the manual:

This function will turn on output buffering. When output buffering is activated, the script will not output content (except http headers), instead the content to be output is stored in an internal buffer.

So this is what I understand:

<code><?php
    ob_start();
    echo 'ob_start'; // 按理说ob_start不应该输出啊。但是确实输出了。</code>

Why is it different from what is described in the manual?

It should be understood that it will not be output to the upper-level buffer immediately. The buffer can be obtained, flushed, cleared, etc. through ob_* related operations. At this time, the output can be unified, such as regular processing, data packaging, etc. .

To make the page static, you can use the ob cache technology provided by php to manually submit the cached content to servers such as apche for processing

<code>$id = isset($_GET['id'])?$_GET['id']-0:0;
$filename = "html/".date("Ymd")."/news-id".$id.".html";
if(!file_exists("html/".date("Ymd"))){
    mkdir("html/".date("Ymd"));
}
echo $filename;
if(!file_exists($filename) || filemtime($filename)+60<time()){
    ob_start();
    require "conn.php";
    $sql = "select * from news where id='$id'";
    $res = $db->query($sql);
    $row = $res->fetch_assoc();
    if($row){
        echo "<table border='1'>";
        echo "<tr>";
        echo "<td>ID</td>";
        echo "<td>标题</td>";
        echo "<td>内容</td>";
        echo "</tr>";
        echo "<tr>";
        echo "<td>".$row['id']."</td>";
        echo "<td>".$row['title']."</td>";
        echo "<td>".$row['content']."</a></td>";
        echo "</tr>";
        echo "</table>";
    }else{
        echo "没有数据";
    }
    $content = ob_get_contents();
    ob_end_clean();
    file_put_contents($filename,$content);
}

require $filename;</code>

That’s because after your script is executed
the buffer will be output
You can add ob_end_clean() after echo;
the buffer will be cleared

It would be weird if it doesn’t output after it’s finished. . . ob just allows us to obtain the rendering results of PHP for caching and the like.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn