zl程序教程

您现在的位置是:首页 >  其它

当前栏目

关于ob_get_contents(),ob_end_clean(),ob_start(),的具体用法详解

详解 用法 关于 get 具体 start end contents
2023-06-13 09:15:02 时间

ob_get_contents();
ob_end_clean();
ob_start()

使用ob_start()把输出那同输出到缓冲区,而不是到浏览器。
然后用ob_get_contents得到缓冲区的数据。
ob_start()在服务器打开一个缓冲区来保存所有的输出。所以在任何时候使用echo,输出都将被加入缓冲区中,直到程序运行结束或者使用ob_flush()来结束。然后在服务器中缓冲区的内容才会发送到浏览器,由浏览器来解析显示。

函数ob_end_clean会清除缓冲区的内容,并将缓冲区关闭,但不会输出内容。
此时得用一个函数ob_get_contents()在ob_end_clean()前面来获得缓冲区的内容。
这样的话,能将在执行ob_end_clean()前把内容保存到一个变量中,然后在ob_end_clean()后面对这个变量做操作。

这是EG:
ob_start();//buf1
echo"multiple";
ob_start();//buf2
echo"bufferswork";
$buf2=ob_get_contents();
ob_end_clean();
$buf1=ob_get_contents();
ob_end_clean();
echo$buf1;
echo"<br/>";
echo$buf2;
ob_get_contents

(PHP4,PHP5)
ob_get_contents--Returnthecontentsoftheoutputbuffer
Description
stringob_get_contents(void)
ThiswillreturnthecontentsoftheoutputbufferorFALSE,ifoutputbufferingisn"tactive.
Seealsoob_start()andob_get_length().
ifyouuseob_startwithacallbackfunctionasaparameter,andthatfunctionchangesobstring(asinexampleinmanual)don"texpectthatob_get_contentswillreturnchangedob.
itwillworkasyouwoulduseob_startwithnoparameteratall.Sodon"tbeconfused.
transferimage,anothermethod(alternativetofsockopenorfunctionsocket):
server(192.168.0.1)
makeimage.php
...........
...........
$nameimage="xxxx.jpg"
$comand=exec("plotvelocity.sh$nameimage$paramater1$paramater2");
ob_start();
readfile($nameimage);
$image_data=ob_get_contents();
ob_end_clean();
echo$image_data;
unlink($nameimage);
Client(192.168.0.2)
$bild="images/newimage2.gif";
$host="192.168.0.1";
$url=file_get_contents("http://$host/makeimage.php?$querystring");
$fp=fopen("$bild","wb");
fwrite($fp,$url);
fclose($fp);
echo"<imgsrc="".$bild."">";
naturallyyoucantransferwhicheverthingandnotonlyimages
ob_get_clean

(PHP4>=4.3.0,PHP5)
ob_get_clean--Getcurrentbuffercontentsanddeletecurrentoutputbuffer
Description
stringob_get_clean(void)
Thiswillreturnthecontentsoftheoutputbufferandendoutputbuffering.Ifoutputbufferingisn"tactivethenFALSEisreturned.ob_get_clean()essentiallyexecutesbothob_get_contents()andob_end_clean().

例子1.Asimpleob_get_clean()example

复制代码代码如下:

<?php
ob_start();
echo"HelloWorld";
$out=ob_get_clean();
$out=strtolower($out);
var_dump($out);
?>

Ourexamplewilloutput:string(11)"helloworld"
Seealsoob_start()andob_get_contents().
Noticethatthefunctionbeneathdoesnotcatcherrors,sothrowinan@beforethoseob_*calls
RunningPHP4<4.3.0,youcansimplyaddthefollowingtousethefunctionanyway:
复制代码代码如下:

<?php
if(!function_exists("ob_get_clean")){
functionob_get_clean(){
$ob_contents=ob_get_contents();
ob_end_clean();
return$ob_contents;
}
}
?>