php 如何将 var_dump 的结果捕获到字符串中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/139474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:38:55  来源:igfitidea点击:

How can I capture the result of var_dump to a string?

phpstringvar-dump

提问by Mark Biek

I'd like to capture the output of var_dumpto a string.

我想捕获var_dump一个字符串的输出。

The PHP documentation says;

PHP 文档说;

As with anything that outputs its result directly to the browser, the output-control functionscan be used to capture the output of this function, and save it in a string (for example).

与直接将结果输出到浏览器的任何内容一样,输出控制函数可用于捕获此函数的输出,并将其保存在字符串中(例如)。

What would be an example of how that might work?

这将如何运作的一个例子是什么?

print_r()isn't a valid possibility, because it's not going to give me the information that I need.

print_r()不是一个有效的可能性,因为它不会给我我需要的信息。

采纳答案by Eran Galperin

Use output buffering:

使用输出缓冲:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>

回答by inxilpro

Try var_export

尝试 var_export

You may want to check out var_export— while it doesn't provide the same output as var_dumpit does provide a second $returnparameter which will cause it to return its output rather than print it:

您可能想要查看var_export- 虽然它提供的输出与var_dump提供的第二个$return参数不同,但它会导致它返回其输出而不是打印它:

$debug = var_export($my_var, true);

Why?

为什么?

I prefer this one-liner to using ob_startand ob_get_clean(). I also find that the output is a little easier to read, since it's just PHP code.

我更喜欢这种单线使用ob_startob_get_clean()。我还发现输出更容易阅读,因为它只是 PHP 代码。

The difference between var_dumpand var_exportis that var_exportreturns a "parsable string representation of a variable"while var_dumpsimply dumps information about a variable. What this means in practice is that var_exportgives you valid PHP code (but may not give you quite as much information about the variable, especially if you're working with resources).

之间的差var_dumpvar_exportvar_export返回一个“可变的可解析的字符串表示”var_dump简单地转储一个变量的信息。这在实践中意味着var_export为您提供有效的 PHP 代码(但可能不会为您提供有关变量的那么多信息,尤其是在您使用资源时)。

Demo:

演示:

$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);

The difference in output:

输出差异:

var_export ($debug_exportin above example):

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_dumpin above example):

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_printrin above example):

print_r($debug_printr在上面的例子中):

Array
(
    [bool] => 
    [int] => 1
    [float] => 3.14
    [string] => hello world
    [array] => Array
        (
        )

    [object] => stdClass Object
        (
        )

    [resource] => Resource id #4
    [null] => 
)

Caveat: var_exportdoes not handle circular references

警告:var_export不处理循环引用

If you're trying to dump a variable with circular references, calling var_exportwill result in a PHP warning:

如果您尝试使用循环引用转储变量,调用var_export将导致 PHP 警告:

 $circular = array();
 $circular['self'] =& $circular;
 var_export($circular);

Results in:

结果是:

 Warning: var_export does not handle circular references in example.php on line 3
 array (
   'self' => 
   array (
     'self' => NULL,
   ),
 )

Both var_dumpand print_r, on the other hand, will output the string *RECURSION*when encountering circular references.

两个var_dumpprint_r,另一方面,将输出串*RECURSION*遇到循环引用时。

回答by Ian P

You could also do this:

你也可以这样做:

$dump = print_r($variable, true);

回答by Sergey Stolyarov

You may also try to use the serialize()function. Sometimes it is very useful for debugging purposes.

您也可以尝试使用该serialize()功能。有时它对于调试目的非常有用。

回答by hanshenrik

function return_var_dump(){
    // It works like var_dump, but it returns a string instead of printing it.
    $args = func_get_args(); // For <5.3.0 support ...
    ob_start();
    call_user_func_array('var_dump', $args);
    return ob_get_clean();
}

回答by ZurabWeb

Also echo json_encode($dataobject);might be helpful

echo json_encode($dataobject);可能有帮助

回答by Younis Bensalah

From the PHP manual:

从 PHP 手册

This function displays structured information about one or more expressions that includes its type and value.

此函数显示有关一个或多个表达式的结构化信息,包括其类型和值。

So, here is the realreturn version of PHP's var_dump(), which actually accepts a variable-length argument list:

所以,这是PHP 的真正返回版本var_dump(),它实际上接受一个可变长度的参数列表:

function var_dump_str()
{
    $argc = func_num_args();
    $argv = func_get_args();

    if ($argc > 0) {
        ob_start();
        call_user_func_array('var_dump', $argv);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    }

    return '';
}

回答by Khandad Niazi

Here is the complete solution as a function:

这是作为函数的完整解决方案:

function varDumpToString ($var)
{
    ob_start();
    var_dump($var);
    return ob_get_clean();
}

回答by selfawaresoup

If you want to have a look at a variable's contents during runtime, consider using a real debugger like XDebug. That way you don't need to mess up your source code, and you can use a debugger even while normal users visit your application. They won't notice.

如果您想在运行时查看变量的内容,请考虑使用像 XDebug 这样的真正调试器。这样你就不需要弄乱你的源代码,即使普通用户访问你的应用程序,你也可以使用调试器。他们不会注意到。

回答by Charlie Vieillard

This maybe a bit off topic.

这可能有点跑题了。

I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.

我一直在寻找一种将此类信息写入 PHP-FPM 容器的 Docker 日志的方法,并想出了下面的代码片段。我确信 Docker PHP-FPM 用户可以使用它。

fwrite(fopen('php://stdout', 'w'), var_export($object, true));