I have read most of the SO questions related to this and I understand that I can use following to download a string as a file in PHP:
header('Content-Disposition: attachment; filename="default-filename.txt"');
echo 'string to download';
However my problem is a bit more. I have something like following:
$csvString = "";
foreach($array as $key => $value)
{
echo "<div> $key has $value</div>";
$csvString = "$key,$value\n";
}
echo "<button> Click here to download as CSV</button>";
As you might have already guessed, I want $csvString to be downloaded when the button is clicked. Any pointers on how I can get that done.
Lets say you have csv.php file, then do:
Basically, if you want all the logic in single file, first check if download is requested and if so prepare it. If no download is request just write your html.