Store print_r result into a variable as a string or text

Php

Php Problem Overview


If I use print_r or var_dump it displays the result on the screen, but I want this data to be stored in a variable so that I can write it to a file.

How do I do this?

Php Solutions


Solution 1 - Php

   $var = print_r($what, true);

You must add true into print_r.

Solution 2 - Php

What you do while you print or dump? Basically you send your data (result or anything) to Show it on screen. Keep your mind clear that its not saved, it is just displayed, To save the data , so a simple thing, just declare a variable and assign the data to it..

for example you are printing some array like this..

print_r(myArray);

to save this, you just have to add an option , set Return to TRUE and assign it to a variable

$myVariable=print_r(myArray, TRUE);

if you need some more information, Follow this

hoping this will help you understanding the concept

Solution 3 - Php

ob_start();
var_dump($someVar);
$result = ob_get_clean();

it works.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaWebDeveloperView Question on Stackoverflow
Solution 1 - PhpgikerView Answer on Stackoverflow
Solution 2 - PhpZaffar SaffeeView Answer on Stackoverflow
Solution 3 - PhpselmonalView Answer on Stackoverflow