code is working properly in Core PHP but writing coding in WordPress

When I attempted something similar I experienced the same issue where the HTML code of the page I was generating the CSV from would be included within the CSV mixed with the data I actually wanted.

The two things I figured out, after searching and reading and reading and searching was to use ob_end_clean(); before I start outputting the content of the CSV. ob_end_clean() is ‘Output Buffers End/Clean` – https://www.php.net/manual/en/function.ob-end-clean.php

I also added die() at the end of the CSV output code to, well, exit the process. You can also use exit().

function generate_pdf( $array ) {
    ob_end_clean(); //ADD THIS LINE
    header( 'Content-Type: text/csv' );
    header('Content-Disposition: attachment; filename="sample.csv"');

    $fp = fopen( 'php://output', 'wb' );
    foreach( $array as $line ) {
        $val = explode( ',', $line );
        fputcsv( $fp, $val );
    }
    fclose( $fp );
    die(); //add this as well
}