0

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!

schustischuster
  • 743
  • 9
  • 29
  • 1
    Did you try Kanchu's answer here: https://stackoverflow.com/questions/13405129/javascript-create-and-save-file ? – icecub Jun 15 '17 at 00:23
  • `I would prefer a pure JavaScript solution` - well, FileSaver.js is a pure javascript solution, and to get the same level of cross browser compatibility as FileSaver.js you would have to write, well, FileSaver.js - perhaps you could explain what it is about FileSaver.js that isn't working "for you" – Jaromanda X Jun 15 '17 at 00:37
  • @ icecub Just had a quick try and it is not working for me right now, but will look into it in more detail. Thanks! – schustischuster Jun 15 '17 at 00:42
  • @Jaromanda I added the code from the example at FileSaver github page ("Saving text using with require") at the end of my JavaScript, also loaded FileSaver.js and Blob.js script links () but no download dialog is opening. I do not know why it doesn't work. – schustischuster Jun 15 '17 at 00:51
  • 1
    any errors in your browsers **developer** tools console? – Jaromanda X Jun 15 '17 at 00:56
  • It says "ReferenceError: require is not defined" Think it refers to: var FileSaver = require('file-saver'); – schustischuster Jun 15 '17 at 01:04
  • @ Jaromanda great tip - if I use FileSaver option without "require" it works:o) This is great thank you so much! – schustischuster Jun 15 '17 at 01:10
  • I have posted the updated script that is functional below as an answer. – schustischuster Jun 27 '17 at 15:04

1 Answers1

0

Thanks to the helpful comments, I could get this running and updated the code to the final version that uses FileSaver.js. The following syntax "saveTextAs(data, filename)" solved the problem. It works for both Firefox and Safari (IE I haven't checked yet). In addition to FileSaver.js, jQuery needs to be loaded for proper functioning of the href link.

First load js libraries:

</script>
<!-- Load jQuery and FileSaver.js here -->
<script src="/path-to-jquery.js"></script>
<script src="/path-to-FileSaver.js"></script>
<script>

Script to convert json object to csv and to open download dialog (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);
    // FileSaver.js: open download dialog and save file as csv
    saveTextAs(csvstring, "data.csv");
     })
    };
</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>        

Thanks everyone for the help!

schustischuster
  • 743
  • 9
  • 29