0

I am using PHPspreadsheet to create xlsx file on xampp. I want to run cron jobs in wordpress that will auto export some orders and save xlsx file on xampp server. I've successfully exported a file using $writer->save('php:\\output'); but this just ask user where to download file.

I want that cron job will save file without asking user. i.e wp-content/export/$filename

Headers:

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="file.xls"');
        header('Cache-Control: max-age=0');

PHP:

$objWriter = new Xlsx($objX);
    
    ob_start();
    $objWriter->save('php://output');
    $xlsData = ob_get_contents();
    ob_end_clean();

    //returning response to javascript
    $response =  array(
        'file_name' =>'s.xlsx',
        'op' => 'ok',
        'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData),
        
    );
    die(json_encode($response));

Javascript

jQuery.ajax({

        url: ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: {
            form_data :detail_info,
            action: 'frontend_action_without_file' // this is going to be used inside wordpress functions.php
        },
        
        error: function(error) {
            
        },
        success: function(response) {
            //console.log("Insert Success" + response.file);
        
        }
    }).done(function(data){
        var $a = jQuery("<a>");
        $a.attr("href",data.file);
        jQuery("body").append($a);
        $a.attr("download",data.file_name);
        $a[0].click();
    
    });
});
King Max
  • 21
  • 1
  • 7

1 Answers1

0

You need to create another page and use a function to download a file from url (in this case your page that generates xlsx), example below.

private function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen ($url, 'rb');
    if ($file) {
        $newf = fopen ($newfname, 'wb');
        if ($newf) {
            while(!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}

downloadFile('https://yoururl.com/generateXlsx.php', 'xlsx/file.xlsx');

after this just execute this shell

* 10 * * * php -f /home/dev/cronjobs/downloadfile.php

this command execute your code every day on 10am /home/dev/cronjobs/downloadfile.php is the file path.

ps. You can use https://crontab-generator.org/ to generate your shell's

naxsi
  • 602
  • 3
  • 15
  • I already have a export button that will manually save the file using ajax. Is there any possibilities that I will use Wp_cron job and hook that function which i mentioned above? Without asking user to download.? – King Max Nov 26 '21 at 13:36