How to capture the result of var_dump to a string in PHP?

PHPServer Side ProgrammingProgramming

The resultant value of var_dumo can be extracted to a string using ‘output buffering’. Below is an example demonstrating the same −

Example

 Live Demo

<?php
   function varDumpToString($var) {
      ob_start();
      var_dump($var);
      $result = ob_get_clean();
      return $result;
   }
   //usage
   $data = array('first', 'second', 'third');
   $result = varDumpToString($data);
   echo $result;

The output control function helps in obtaining the output of a function and saving it to a string variable. In general, the output of a PHP code is usually displayed on a browser.

Output

This will produce the following output −

array(3) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(5) "third" }
raja
Published on 30-Dec-2019 06:37:45
Advertisements