I am trying to write a code that will convert my php array into csv and then open a download dialog (save.As()) so that the website user can download the file after clicking on an html href link.
After searching a lot of posts, I could already come up with a solution in JavaScript that enables me to convert the php array to csv and display the result on the webpage to check if this is functioning and indeed it is.
I tried hard to also get the download dialog working, but had no success so far. I was trying FileSaver.js but this one just won't work for me. I would prefer a pure JavaScript solution that would work for IE, Safari and Firefox without additional libraries.
Here is my script so far to convert json object to csv and to display result on screen (this is mostly based on another script found at SO, but I cannot find the source again - if someone knows, I would be happy to include a link here):
<script type="text/javascript">
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function download_csv_function() {
// Read in JSON data and transform to CSV
$(document).ready(function () {
// Read in json data
var items = <?php echo $jsonout; ?>;
// Convert JSON object into JSON string
var jsonObject = JSON.stringify(items);
// Convert JSON to CSV
var csvstring = ConvertToCSV(jsonObject);
$('#csv').text(csvstring);
})
};
</script>
Include a link in html:
</form>
<!-- Define "Download .csv link here" -->
<a href="javascript:void(0)" onclick="download_csv_function();" >Get data as csv file</a>
</form>
<body>
<pre id="csv"></pre>
</body>
Thanks!