Array-to-CSV-export function encounters a problem in WordPress plugin

I use the simple export function to CSV file on my plugin page to create a report.

When I run this code, I get an error message that it will export all html content along with my expected array.

Here is my code:

function convert_to_csv($input_array, $output_file_name, $delimiter) { clearstatcache(); /** open raw memory as file, no need for temp files */ $temp_memory = fopen('php://memory', 'w'); /** loop through array */ foreach ($input_array as $line) { /** default php csv handler **/ fputcsv($temp_memory, $line, $delimiter); } //echo '<pre>'; //print_r($temp_memory); exit; /** rewrind the "file" with the csv lines **/ fseek($temp_memory, 0); /** modify header to be downloadable csv file **/ header('Content-Type: application/csv'); header('Content-Disposition: attachement; filename="' . $output_file_name . '";'); /** Send file to browser for download */ fpassthru($temp_memory); } /** Array to convert to csv */ $array_to_csv = Array( Array(12566, 'Enmanuel', 'Corvo' ), Array(56544, 'John', 'Doe' ), Array(78550, 'Mark', 'Smith' ) ); clearstatcache(); convert_to_csv($array_to_csv, 'report.csv', ','); 
+9
arrays php csv wordpress
source share
2 answers

I assume that WP continues to perform its usual operations after calling this function, so you will get the HTML template after CSV. Entering the exit statement after fpassthru should do this, but you need to be careful not to mess up anything Wordpress does at the end of every response to the page. Drupal, for example, has a drupal_exit() function just for this purpose. I'm not familiar with WP enough to know for sure, but the documentation for the wp_die () function suggests that you can use PHP exit without much trouble

0
source share

You can use this code to create an Excel file with the extension .xlsx

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.12/xlsx.core.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var insuranceArray = new Array(insuranceInfo); var bills = db.bills; //Create tabs in excel file var opts = [{sheetid:'Insurance Information',header:true},{sheetid:'bills Info',header:false}]; alasql('SELECT * INTO XLSX("Data.xlsx",?) FROM ?', [opts, insuranceArray,bills]]); // Close the window once you save the file window.onfocus=function(){ window.close(); } </script> 

This code works for me ...

0
source share

All Articles