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
print_
var_dump
$var = print_r($what, true);
You must add true into print_r.