MOHIT GUSAIN
MOHIT GUSAIN

Reputation: 25

I want to download the data into the CSV format using php spreadsheets

    add_action('admin_post_learning_profile_csv_download', 'learning_profile_csv_download');
    function learning_profile_csv_download(){
        $spreadsheet = new Spreadsheet();  
        $Excel_writer = new Xls($spreadsheet);  
        $spreadsheet->setActiveSheetIndex(0);
        $activeSheet = $spreadsheet->getActiveSheet();
        $activeSheet->setCellValue('A1' , 'New file content')->getStyle('A1')->getFont()->setBold(true);  
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'. $filename .'.csv"'); 
        header('Cache-Control: max-age=0');
        $Excel_writer->save('php://output');
        $user_id = get_current_user_id();
        echo $user_id;
        echo '<br>';
        $learning_plan = get_user_meta( get_current_user_id(), 'study_guide', true);
        if( empty( $learning_plan ) ) {
            echo 'No Resources Currently Recommended.';
        } else {
            foreach( $learning_plan as $item ) {
                $resource_comps = get_the_terms( $item, 'ivpt_cc' );
                echo get_the_title($item);
                foreach( $resource_comps as $comp ){
                    echo $comp->name;
                    echo'<br>';
                }
            }
        }
    }

This is my code I want to download the learning plan data into CSV format into two columns once into the title and another column for comp->name. So how I set a column and row into the foreach loop for learning plan?

Upvotes: 2

Views: 107

Answers (1)

Guy Louzon
Guy Louzon

Reputation: 1203

With a few modifications to your foreach loop Notice that you cannot echo any html in parallel, that is echo with a <br> tag ...

Hope that helps

$title = get_the_title($item);
$csv = "";

foreach ( $resource_comps as $comp ){
 $csv .= "'" . $title . "','" . $comp->name . "\r\n";
}
header('Content-type: text/csv');
echo $csv;

Upvotes: 1

Related Questions