如何将 echo() 的结果捕获到 PHP 中的变量中?
我正在使用一个 PHP 库来回显结果而不是返回结果。有没有一种简单的方法来捕获 echo/print 的输出并将其存储在变量中? (其他文本已输出,并且未使用输出缓冲。)
I'm using a PHP library that echoes a result rather than returns it. Is there an easy way to capture the output from echo/print and store it in a variable? (Other text has already been output, and output buffering is not being used.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用输出缓冲:
但这不是一个干净且有趣的语法。找到一个更好的图书馆可能是个好主意......
You could use output buffering :
But it's not a clean and fun syntax to use. It may be a good idea to find a better library...
我知道的唯一方法。
The only way I know.
如果可以的话,你真的应该重写这个类。我怀疑找到 echo/print 语句并用
$output .=
替换它们会那么困难。使用 ob_xxx 确实需要资源。You should really rewrite the class if you can. I doubt it would be that hard to find the echo/print statements and replace them with
$output .=
. Using ob_xxx does take resources.在应用程序完全完成之前不要回显数据始终是一个好的做法,例如
现在
session_start
以及另一串函数将无法工作,因为已经有数据作为响应输出,但通过执行以下操作:这可行且不易出错,但如果您必须捕获输出,那么您会这样做:
Its always good practise not to echo data until your application as fully completed, for example
now
session_start
along with another string of functions would not work as there's already been data outputted as the response, but by doing the following:This would work and its less error prone, but if its a must that you need to capture output then you would do: