programing

var_dump의 결과를 문자열로 캡처하려면 어떻게해야합니까?

nasanasas 2020. 10. 3. 10:55
반응형

var_dump의 결과를 문자열로 캡처하려면 어떻게해야합니까?


의 출력을 var_dump문자열 로 캡처하고 싶습니다 .

PHP 문서에 따르면;

결과를 브라우저에 직접 출력하는 모든 것과 마찬가지로 출력 제어 함수 를 사용하여이 함수의 출력을 캡처하고 문자열에 저장할 수 있습니다 (예 :).

그것이 어떻게 작동 할 수 있는지에 대한 예는 무엇입니까?

print_r() 타당한 가능성이 아닙니다. 필요한 정보를 제공하지 않기 때문입니다.


출력 버퍼링 사용 :

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

시험 var_export

체크 아웃을 원할 수 있습니다 . 두 번째 매개 변수를 var_export제공하는 것과 동일한 출력을 제공하지는 않지만 출력 대신 출력을 반환하도록합니다.var_dump$return

$debug = var_export($my_var, true);

왜?

이 한 줄짜리가 ob_startob_get_clean(). 또한 출력은 PHP 코드 일 뿐이므로 읽기가 조금 더 쉽습니다.

의 차이 var_dump와는 var_exportvar_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순환 참조를 처리하지 않습니다 .

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

 $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_dump and print_r, on the other hand, will output the string *RECURSION* when encountering circular references.


You could also do this:

$dump = print_r($variable, true);

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


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();
}

Also echo json_encode($dataobject); might be helpful


From the PHP manual:

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

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

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 '';
}

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.


Here is the complete solution as a function:

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

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.

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

I really like var_dump()'s verbose output and wasn't satisfied with var_export()'s or print_r()'s output because it didn't give as much information (e.g. data type missing, length missing).

To write secure and predictable code, sometimes it's useful to differentiate between an empty string and a null. Or between a 1 and a true. Or between a null and a false. So I want my data type in the output.

Although helpful, I didn't find a clean and simple solution in the existing responses to convert the colored output of var_dump() to a human-readable output into a string without the html tags and including all the details from var_dump().

Note that if you have a colored var_dump(), it means that you have Xdebug installed which overrides php's default var_dump() to add html colors.

For that reason, I created this slight variation giving exactly what I need:

function dbg_var_dump($var)
    {
        ob_start();
        var_dump($var);
        $result = ob_get_clean();
        return strip_tags(strtr($result, ['=&gt;' => '=>']));
    }

Returns the below nice string:

array (size=6)
  'functioncall' => string 'add-time-property' (length=17)
  'listingid' => string '57' (length=2)
  'weekday' => string '0' (length=1)
  'starttime' => string '00:00' (length=5)
  'endtime' => string '00:00' (length=5)
  'price' => string '' (length=0)

Hope it helps someone.


Long string: Just use echo($var); instead of dump($var);.

Object or Array: var_dump('<pre>'.json_encode($var).'</pre>);'


From http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html:

var_dump and print_r functions can only output directly to browser. So the output of these functions can only retrieved by using output control functions of php. Below method may be useful to save the output.

function assignVarDumpValueToString($object) {
    ob_start();
    var_dump($object);
    $result = ob_get_clean();
    return $result;
}

ob_get_clean() can only clear last data entered to internal buffer. So ob_get_contents method will be useful if you have multiple entries.

From the same source as above:

function varDumpToErrorLog( $var=null ){
    ob_start();                    // start reading the internal buffer
    var_dump( $var);          
    $grabbed_information = ob_get_contents(); // assigning the internal buffer contents to variable
    ob_end_clean();                // clearing the internal buffer.
    error_log( $grabbed_information);        // saving the information to error_log
}

참고URL : https://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string

반응형