Have you ever needed to convert a 2 dimensional array into a CSV then force a download? Well, I have, and here is how I did it:
Every internal array must have the same keys. These keys may be set to null, but the key must exist. Below is a sample array that we can work with through this example.
[ [ 'title'=>'How to be Good at Life', 'author'=>'@GRTaylor2', 'url'=>'https://medium.com/better-humans/56302026d56e' ], [ 'title'=>'Clean URLs for Good SEO', 'author'=>'@ChuckReynolds', 'url'=>'http://rynoweb.com/clean-urls-good-seo/' ] ]
The code (below) takes the array (above) and converts it into a CSV string with the keys being the header row. After the string is generated, it is placed into output buffer then forced to be downloaded by the browser.
Once the CSV is generated, it will be downloaded. This is what the CSV file will look like:
title,author,url "How to be Good at Life",@GRTaylor2,https://medium.com/better-humans/56302026d56e "Clean URLs for Good SEO",@ChuckReynolds,http://rynoweb.com/clean-urls-good-seo/
CSV output is an annoying part of reporting in PHP. Hopefully this simple solution makes it easier in the future.