search
Homephp教程php手册outputbuffer输出缓冲函数的妙用

outputbuffer输出缓冲函数的妙用

Jun 13, 2016 am 10:29 AM
bufferoutput

在PHP编程中, 我们经常会遇到一些直接产生输出的函数, 如passthru(),readfile(), var_dump() 等. 但有时我们想把这些函数的输出导入到文件中,或者先经过处理再输出, 或者把这些函数的输出作为字符串来处理.
这时我们就要用到 Output Buffer(输出缓冲) 函数了.

处理输出缓冲的函数主要有这么几个:

ob_start() 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.

ob_get_contents() 这个函数返回内部缓冲的内容. 这就等于把这些输出都变成了字符串.

ob_get_ length() 返回内部缓冲的长度.

ob_end_flush() 结束输出缓冲, 并输出缓冲里的内容. 在这以后的输出都是正常输出.

ob_end_clean() 结束输出缓冲, 并扔掉缓冲里的内容.

举个例子, var_dump()函数输出一个变量的结构和内容, 这在调试的时候很有用.
但如果变量的内容里有 < , > 等HTML的特殊字符, 输出到网页里就看不见了. 怎么办呢?
用输出缓冲函数能很容易的解决这个问题.

ob_start();
var_dump($var);
$out = ob_get_contents();
ob_end_clean();

这时var_dump()的输出已经存在 $out 里了. 你可以现在就输出:

echo '

' . htmlspecialchars($out) . '
' ;

或者等到将来, 再或者把这个字符串送到模板(Template)里再输出.

更多相关教程请访问   php编程从入门到精通全套视频教程

Statement
This article is reproduced at:CSDN博客. If there is any infringement, please contact admin@php.cn delete

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)