Heim  >  Artikel  >  Backend-Entwicklung  >  php ob_start()缓存函数的用法详解

php ob_start()缓存函数的用法详解

WBOY
WBOYOriginal
2016-07-25 08:56:481004Durchsuche
本文介绍下,php中用于缓存控制的函数ob_start()的用法,有需要的朋友参考下吧。

在php中,ob_start()函数用于打开缓冲区,比如header()函数之前如果就有输出,包括回车/空格/换行/都会有"Header had all ready send by"的错误。

此时可以先用ob_start()打开缓冲区php代码的数据块和echo()输出都会进入缓冲区而不会立刻输出。

对于php中打开缓冲区的方法,总结为四种: 1,用于header()之前

<?php
ob_start(); //打开缓冲区 
echo /"Hellon/"; //输出 
header("location:index.php"); //把浏览器重定向到index.php 
ob_end_flush();//输出全部内容到浏览器 
?>

2,phpinfo()函数可获取客户端和服务器端的信息,保存客户端信息用缓冲区。

<?php
ob_start(); //打开缓冲区 
phpinfo(); //使用phpinfo函数 
$info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info 
$file=fopen(/'info.txt/',/'w/'); //打开文件info.txt 
fwrite($file,$info); //写入信息到info.txt 
fclose($file); //关闭文件info.txt 
?>

3,静态页面技术

<?php
ob_start();//打开缓冲区 
 
//php页面的全部输出 
$content = ob_get_contents();//取得php页面输出的全部内容 
$fp = fopen("output00001.html", "w"); //创建一个文件,并打开,准备写入 
fwrite($fp, $content); //把php页面的内容全部写入output00001.html,然后…… 
fclose($fp); 
?> 

4,输出代码

<?php
Function run_code($code) { 
If($code) { 
   ob_start(); 
   eval($code); 
   $contents = ob_get_contents(); 
   ob_end_clean(); 
}else { 
   echo "错误!没有输出"; 
   exit(); 
} 
   return $contents; 
}


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn