search
Homephp教程php手册Output Buffer(输出缓冲)函数的妙用

Output Buffer(输出缓冲)函数的妙用

Jun 13, 2016 am 10:22 AM
bufferoutputphpfunctionexistmagical effectusofbufferprogrammingoutputmeet


  在PHP编程中, 我们经常会遇到一些直接产生输出的函数, 如passthru(),readfile(), var_dump() 等. 但有时我们想把这些函数的输出导入到文件中,或者先经过处理再输出, 或者把这些函数的输出作为字符串来处理.
  这时我们就要用到 Output Buffer(输出缓冲) 函数了.
  处理输出缓冲的函数主要有这么几个:
ob_start() 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.
ob_get_contents() 这个函数返回内部缓冲的内容. 这就等于把这些输出都变成了字符串.
ob_get_ length() 返回内部缓冲的长度.
ob_end_flush() 结束输出缓冲, 并输出缓冲里的内容. 在这以后的输出都是正常输出.
ob_end_clean() 结束输出缓冲, 并扔掉缓冲里的内容.
  举个例子, var_dump()函数输出一个变量的结构和内容, 这在调试的时候很有用.
  但如果变量的内容里有 $#@60; , $#@62; 等HTML的特殊字符, 输出到网页里就看不见了. 怎么办呢?
  用输出缓冲函数能很容易的解决这个问题.
ob_start();
var_dump($var);
$out = ob_get_contents();
ob_end_clean();
  这时var_dump()的输出已经存在 $out 里了. 你可以现在就输出:
echo "$#@60;pre$#@62;" . htmlspecialchars($out) . "$#@60;/pre$#@62;" ;
  或者等到将来, 再或者把这个字符串送到模板(Template)里再输出.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.