如何防止PHP中的回声并捕获它里面的内容?

ilh*_*han 16 php string echo

我有一个函数(DoDb::printJsonDG($sql, $db, 1000, 2)),其中echos json.我必须捕获它,然后在发送给用户之前使用str_replace().但是我不能阻止它做回声.我不想更改printJsonDG,因为它正在其他几个地方使用.

oli*_*ier 47

您可以 在PHP中使用ob_start()ob_get_contents()函数.

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>
Run Code Online (Sandbox Code Playgroud)

将输出:

string(6) "Hello "
string(11) "Hello World"
Run Code Online (Sandbox Code Playgroud)


N.B*_*.B. 6

您可以使用输出缓冲功能来完成.

ob_start();

/* do your echoing and what not */ 

$str = ob_get_contents();

/* perform what you need on $str with str_replace */ 

ob_end_clean();

/* echo it out after doing what you had to */

echo $str;
Run Code Online (Sandbox Code Playgroud)