我们可以在标题之前有一个回声吗

我们可以在标题之前有一个回声吗

本文介绍了面试问题:我们可以在标题之前有一个回声吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参加了 php 测试,他们问了一个我找不到答案的问题.

I appeared for php test, their I was asked one question for which I could not find the answer.

问题是这样的.

echo "MESSI is injured!!";
header("Location:somepage.php");

面试官希望 headerecho 写在同一页面上.

Interviewer want both header and echo to be written on the same page.

我想知道这怎么可能.它应该给出一些错误,例如

I wonder how's it possible.It should give some error like

已发送的标头(输出开始于.....

真的可以将echo和header写到同一个页面吗!!!

Is it really possible to write echo and header onto same page !!!

推荐答案

你可以使用 输出缓冲 as

ob_start();
echo "MESSI is injured!!";
header("Location:somepage.php");
ob_end_flush();

问题是我们开始发送输出后无法发送标头.为了解决这个问题,我们缓冲输出.ob_start 函数打开输出缓冲.当输出缓冲处于活动状态时,不会从脚本发送输出(除了标题),而是将输出存储在内部缓冲区中.所以 echo 输出将被缓冲.接下来我们发送标题没有任何问题,因为我们还没有吐出任何输出.最后我们调用 ob_end_flush 来刷新内部缓冲区内容并停止输出缓冲.

The problem is that we cannot send the header after we start sending the output. To solve this we buffer the output. The function ob_start turns output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So the echo output will be buffered. Next we send the header without any problem as we've not yet spit out any output. Finally we call ob_end_flush to flush the internal buffer contents and to stop output buffering.

这篇关于面试问题:我们可以在标题之前有一个回声吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:54