如何将 PHP 数组中的所需字段导出到 Javascript 中的 JSON/CSV

How to export desired fields from PHP array to JSON/CSV in Javascript

我是 php 和 javascript 的新手,抱歉我的英语不好。我已经搜索并阅读了很多关于此的主题,但对我没有任何用处。

我需要了解如何将 json 文件的某些字段导出到 CSV 或 excel 中,其中一些字段(而不是全部)已准备好下载。

我设法获得了一个 json 输出,其中包含一组数据,并通过单击按钮将其打印在控制台中。这是 php 文件中的脚本。 现在我需要将此输出转换为 CSV 格式并能够下载它。

这是我将数组存储在 var json 中的 js 代码:

            <a id="csv_btn" class= "btn btn-primary btn-sm pull-right" 
             
            onclick="download_csv()">Download CSV</a>

            <div class="js-search-box"></div>
    
        
<script type="text/javascript">

                var json = <?php echo json_encode($outjson); ?>;
                
                function download_csv () {
                var formId = document.getElementById("csv_btn");
                window.alert("Do yow want to download CSV?");
    
                console.log(json);
        
            }
                     
</script>

在附件的图片中,有点击下载后的输出。

提前致谢

enter image description here enter image description here

编辑:

经过多次尝试,我发现一个代码运行良好;感谢 Danny Pule 在 this link

找到

现在,我正在尝试弄清楚如何创建过滤器以排除或包含某些字段并获取包含所需字段的 CSV。另外,如果有人可以向我解释如何从这个 json 文件中打印 [object Object] 的字段中提取数据(即在“机器”字段中有另一个数组)

enter image description here

下面的代码:

<!--gabri-->
            
            <a id="csv_btn" class= "btn btn-primary btn-sm pull-right" onclick="exportCSVFile(headers, itemsFormatted, fileTitle)">Download CSV</a>

            <div class="js-search-box"></div>
                    
        
<script type="text/javascript">

                var datajson = <?php echo json_encode($outjson); ?>;
                
                //download_csv(datajson);
        
                function convertToCSV(objArray) {
                    
                     var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
                    
                    window.alert("Do yow want to download CSV?");
                     
                     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 exportCSVFile(headers, items, fileTitle) {
                    if (headers) {
                        items.unshift(headers);
                    }
                
                    // Convert Object to JSON
                    var jsonObject = JSON.stringify(items);
                
                    var csv = this.convertToCSV(jsonObject);
                
                    var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
                
                    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                    if (navigator.msSaveBlob) { // IE 10+
                        navigator.msSaveBlob(blob, exportedFilenmae);
                    } else {
                        var link = document.createElement("a");
                        if (link.download !== undefined) { // feature detection
                            // Browsers that support HTML5 download attribute
                            var url = URL.createObjectURL(blob);
                            link.setAttribute("href", url);
                            link.setAttribute("download", exportedFilenmae);
                            link.style.visibility = 'hidden';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            console.log(datajson);
                        }
                    }
                }

var headers = {
    label: 'Project Name'.replace(/,/g, ''), // remove commas to avoid errors
    id: "id".replace(/,/g, ''),
    active: "active",
    start_date: "Start Date".replace(/,/g, ''),
    year:"Year",
    coord: "Coord",
    perc: "perc",
    plants:"Total Plants",
    done: "Plants done",
    machine: "Machine"
};

//itemsNotFormatted = [];

var obj = JSON.parse([datajson]);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
//var values = Object.keys(obj).forEach(key => { console.log(key, obj[key]);});
console.log(values);

var itemsFormatted = values;

// format the data
/*itemsNotFormatted.forEach((item) => {
    itemsFormatted.push({
       label: item.label.replace(/,/g, ''), // remove commas to avoid errors,
        id: item.id,
        start_date: item.start_date,
        coord: item.coord,
        perc: item.perc,
        plants: item.plants,
        done: item.done,
        machine: item.machine
    });
});
*/
var fileTitle = 'monitor-report'; // or 'my-unique-title'

//exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download
                    
   
</script>

这是我从php

得到的数据json
[{"label":"garbuiodiadoragrande","id":2176216,"active":0,"start_date":"23 mag, 2018","end_date":null,"perc":0.061996280223187,"plants":1613,"done":1,"machines":[{"label":"Trattore test 02 2016","id":3003}],"client":null,"client_id":null,"source":{"label":"Trattore test 02 2016","id":3003},"center_lat":45.777920164083,"center_lon":12.007139535756,"page":"\/customer\/projects\/2176216\/"},{"label":"prova","id":2176008,"active":0,"start_date":"21 mag, 2018","end_date":null,"perc":0.44247787610619,"plants":3842,"done":17,"machines":[{"label":"Trattore test 02 2016","id":3003}],"client":null,"client_id":null,"source":{"label":"Trattore test 02 2016","id":3003},"center_lat":43.830309706033,"center_lon":11.206148940511,"page":"\/customer\/projects\/2176008\/"}

下面的图片是我在 console.log(值)中从 Object.map 得到的结果,但我不确定方法是否正确而且我很困惑。

enter image description here 感谢您的任何建议

编辑: 好的,我有一个代码可以工作并过滤所需的字段

                <script type="text/javascript">


                    Date.prototype.today = function () { 
                        return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
                    }

                    // For the time now
                    Date.prototype.timeNow = function () {
                        return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
                    }


                    var datetime = " @ " + new Date().today() + " @ " + new Date().timeNow();
                    var fileTitle = 'monitor-report'+ datetime; // or 'my-unique-title'
                    var datajson = <?php echo json_encode($outjson); ?>;
                    var itemsFormatted = JSON.parse([datajson]);

                    
                    
                    //download_csv(datajson);
                    
                    function convertToCSV(objArray) {
                        
                        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

                        window.alert("Do yow want to download CSV?");
                        
                        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 exportCSVFile(headers, items, fileTitle) {
                        if (headers) {
                            items.unshift(headers);
                        }
                        
                        // Convert Object to JSON
                        var jsonObject = JSON.stringify(items,
                            ['label',
                            'id',
                            'start_date',
                            'year',
                            'end_date',
                            'perc',
                            'plants',
                            'done']);

                        
                        var csv = this.convertToCSV(jsonObject);
                        
                        var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
                        
                        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                        if (navigator.msSaveBlob) { // IE 10+
                            navigator.msSaveBlob(blob, exportedFilenmae);
                        } else {
                            var link = document.createElement("a");
                            if (link.download !== undefined) { // feature detection
                                // Browsers that support HTML5 download attribute
                                var url = URL.createObjectURL(blob);
                                link.setAttribute("href", url);
                                link.setAttribute("download", exportedFilenmae);
                                link.style.visibility = 'hidden';
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                                console.log(jsonObject);
                            }
                        }
                    }

                    var headers = {
                                    label: 'Project Name'.replace(/,/g, ''), // remove commas to avoid errors
                                    id: "id",
                                    active: "active",
                                    start_date: "Start Date".replace(/,/g, ''),
                                    year:"Year",
                                    end_date:"End Date",
                                    perc: "perc",
                                    coord: "Coord",
                                    plants:"Total Plants",
                                    done: "Plants done",
                                };
                                
                    //console.log(datajson);


                </script>


但我不知道如何在主数组中提取另一个数组。在 "machines":[{"label":"Trattore test 02 2016","id":3003}] 中,我需要标签和 ID。 任何人都可以帮助我)

[{"label":"garbuio diadoragrande","id":2176216,"active":0,"start_date":"23 mag,2018",
"end_date":null,"perc":0.061996280223187,"plants":1613,"done":1,
"machines":[{"label":"Trattore test 02 2016","id":3003}],
"client":null,"client_id":null,"source":{"label":"Trattore test 02 2016","id":3003},"center_lat":45.777920164083,"center_lon":12.007139535756,"page":"\/customer\/projects\/2176216\/"},

我终于得到了一个工作代码。可能它并不完美,但它确实有效! 这是代码,如果它可能对某人有用。

感谢社区


<script type="text/javascript">


                    Date.prototype.today = function () { 
                        return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
                    }

                    // For the time now
                    Date.prototype.timeNow = function () {
                        return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
                    }


                    var datetime = " @ " + new Date().today() + " @ " + new Date().timeNow();
                    var fileTitle = 'Report_Monitor'+ datetime; // or 'my-unique-title'

                    var datajson = <?php echo json_encode($outjson); ?>;
                    var itemsFormatted = JSON.parse([datajson]);

                    //var itemsFormatted = obj;

                    
                    
                    function convertToCSV(objArray) {
                        
                        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

                        window.alert("Do yow want to download CSV?");
                        
                        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 exportCSVFile(headers, items, fileTitle) {
                        if (headers) {
                            items.unshift(headers);
                        }
                        
                        // Convert Object to JSON
                        var jsonObject = JSON.stringify(items,
                            ['label',
                            'id',
                            "start_date".replace(/,/g, ' '),
                            'end_date',
                            'perc',
                            'plants',
                            'done',
                            'center_lat',
                            'center_lon']);


                        var jsonObjectFiltered = jsonObject.replace(/,(?!["{}[\]])/g, "");

                        console.log(jsonObjectFiltered);
                        
                        var csv = this.convertToCSV(jsonObjectFiltered).replace(/null/g,"0");
                        
                        var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
                        
                        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                        if (navigator.msSaveBlob) { // IE 10+
                            navigator.msSaveBlob(blob, exportedFilenmae);
                        } else {
                            var link = document.createElement("a");
                            if (link.download !== undefined) { // feature detection
                                // Browsers that support HTML5 download attribute
                                var url = URL.createObjectURL(blob);
                                link.setAttribute("href", url);
                                link.setAttribute("download", exportedFilenmae);
                                link.style.visibility = 'hidden';
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                                console.log(jsonObject);
                            }
                        }
                    }

                    var headers = {
                                    label: 'Project Name', // remove commas to avoid errors
                                    id: 'id',
                                    active: 'active',
                                    start_date: 'Start Date',
                                    //year:'Year',
                                    end_date:'End Date',
                                    perc: 'Percentage',
                                    plants:'Total Stakes',
                                    done: 'Stakes Done',
                                    center_lat: 'Lat',
                                    center_lon: 'Lon'
                                };

                    //console.log(datajson);


                </script>