如何将var_dump的结果捕获到字符串?
时间:2020-03-06 14:47:00 来源:igfitidea点击:
我想将var_dump的输出捕获到一个字符串中。
PHP文档说;
As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).
谁能给我一个例子,说明它可能如何工作?
" print_r()"不是一种有效的方法,因为它不会给我所需的信息。
解决方案
使用输出缓冲:
<?php ob_start(); var_dump($someVar); $result = ob_get_clean(); ?>
我们也可以这样做:
$dump = print_r($variable, true);
我们可能想签出var_export,但它没有提供与var_dump相同的输出,而是提供了第二个$ return参数,这将导致它返回输出而不是打印输出:
$debug = var_export($my_var, true);
为什么?
我更喜欢这种单行代码而不是使用ob_start和ob_get_clean()。我还发现该输出更易于阅读,因为它只是PHP代码。
" var_dump"和" var_export"之间的区别在于," var_export"返回"变量的可解析字符串表示形式",而" var_dump"仅转储有关变量的信息。实际上,这意味着var_export为我们提供有效的PHP代码(但可能不会为我们提供有关变量的足够多的信息,尤其是在使用资源的情况下)。
演示:
$demo = array(
"bool" => false,
"int" => 1,
"float" => 3.14,
"string" => "hello world",
"array" => array(),
"object" => new stdClass(),
"resource" => tmpfile(),
"null" => null,
);
// var_export -- nice, one-liner
$debug_export = var_export($demo, true);
// var_dump
ob_start();
var_dump($demo);
$debug_dump = ob_get_clean();
// print_r -- included for completeness, though not recommended
$debug_printr = print_r($demo, true);
输出的差异:
var_export(在上例中为$ debug_export`):
array ( 'bool' => false, 'int' => 1, 'float' => 3.1400000000000001, 'string' => 'hello world', 'array' => array ( ), 'object' => stdClass::__set_state(array( )), 'resource' => NULL, // Note that this resource pointer is now NULL 'null' => NULL, )
var_dump(以上示例中的$ debug_dump):
array(8) {
["bool"]=>
bool(false)
["int"]=>
int(1)
["float"]=>
float(3.14)
["string"]=>
string(11) "hello world"
["array"]=>
array(0) {
}
["object"]=>
object(stdClass)#1 (0) {
}
["resource"]=>
resource(4) of type (stream)
["null"]=>
NULL
}
print_r(上面例子中的$ debug_printr):
Array
(
[bool] =>
[int] => 1
[float] => 3.14
[string] => hello world
[array] => Array
(
)
[object] => stdClass Object
(
)
[resource] => Resource id #4
[null] =>
)
注意:var_export不处理循环引用
如果我们尝试使用循环引用转储变量,则调用var_export将导致PHP警告:
$circular = array(); $circular['self'] =& $circular; var_export($circular);
结果是:
Warning: var_export does not handle circular references in example.php on line 3
array (
'self' =>
array (
'self' => NULL,
),
)
另一方面,当遇到循环引用时,var_dump和print_r都将输出字符串* RECURSION *。
我们也可以尝试使用serialize()函数,有时对于调试目的非常有用。
如果要在运行时查看变量内容,请考虑使用真正的调试器,例如XDebug。这样,我们无需弄乱源代码,即使普通用户访问应用程序,也可以使用调试器。他们不会注意到。

