Exporting a CSV of product data, from a woocommerce single page

Hi there

I’ve coded a function to download a CSV of product data from a woocommerce single product page. However, the code seems to output the entire page code to the csv then download it. I’m only after a few product attributes, such as ID and sku.

<?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");
$product = array ($prodID, $prodDesc);

// Write to the csv
fputcsv($f, [$product]);

// Close the file
fclose($f);
// ... download will start
		} ?>
		
		<form method="post"> 
    <input type="submit" name="button1" class="button" value="Button1" /> 
</form> 
Sponsor our Newsletter | Privacy Policy | Terms of Service