'Woocommerce, export product meta to CSV via front end

I'm trying to code a button in Woocommerce so that once clicked, it downloads a CSV with single product metadata in it. The code is below. At the moment the CSV downloads but it is literally all the code on the page. I just want it to be some Woocommerce attribute variables.

See: https://www.codewall.co.uk/automatically-download-csv-file-in-php

<?php echo $product->get_id(); 
        echo $product->get_slug();
        echo $product->get_date_created();
        echo $product->get_date_modified();
        echo $product->get_status();
        echo $product->get_featured();
        echo $product->get_catalog_visibility();
        echo $product->get_description();
        echo  $product->get_short_description();
        echo $product->get_sku();
        echo $product->get_menu_order();
        echo $product->get_virtual();
        echo  get_permalink( $product->get_id() );  
    
    ?>      
    
    <!-- https://www.codewall.co.uk/automatically-download-csv-file-in-php/ -->
    <?php 
    
    if(array_key_exists('button1', $_POST)) { 
   printCSV(); 
} 
else if(array_key_exists('button2', $_POST)) { 
    button2(); 
} 

    $prodID = $product->get_id();
    $prodDesc = $product->get_short_description();
    
    function printCSV() {
    // Set the content type
header('Content-type: application/csv');
// Set the file name option to a filename of your choice.
header('Content-Disposition: attachment; filename=productDetails.csv');
// Set the encoding
header("Content-Transfer-Encoding: UTF-8");
// Write to the csv
fputcsv($f, [$prodID,$prodDesc]);

// Close the file
fclose($f);
// ... download will start
    } ?>
    
    <form method="post"> 
      <input type="submit" name="button1" class="button" value="Button1" /> 
    </form> 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source