firenemus
firenemus

Reputation: 165

PHP array to CSV Download - Unwanted data in the first column header

I'm using ajax to post array data, and on success have it download a csv file. Everything works fine except I'm getting some extra data (string) in the first column header. How do I get rid of this?

Here's my JS:

<!-- Submit Roster ------------------------------------------------------------>
<script>
$('#downloadRosterCSV').on("click", function() {
//$('.loading').show();

var email = [];
var name = [];
var id = [];
var gclass = <?php echo '"'.$courseNAME. '.csv"' ?>;

$("input:checkbox[class=ckbRoster]:checked").each(function() { 
                email.push($(this).attr("email"));
                name.push($(this).attr("name"));
            }); 


    $.ajax({
        type: "POST",
        url: "csv.php",
        data: {email: email, name: name, gclass: gclass},
        dataType: 'html',
        cache: false,
        //success: function() {window.location.assign(<?php echo '"temp/rosters/' . $courseNAME. '.csv"' ?>);$('.loading').hide();},
        //success: function() {window.location.assign("csv.php");}, 
        success: function(data){

              /*
               * Make CSV downloadable
               */
              var downloadLink = document.createElement("a");
              var fileData = ['\ufeff'+data];

              var blobObject = new Blob(fileData,{
                 type: "text/csv;charset=utf-8;"
               });

              var url = URL.createObjectURL(blobObject);
              downloadLink.href = url;
              downloadLink.download = <?php echo '"' . $courseNAME. '.csv"' ?>;

              /*
               * Actually download CSV
               */
              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);

        }
            }); 
});

</script>
<!-- END ---------------------------------------------------------------------->

And here's my PHP:

<?php
session_start();
header("Content-Type: text/csv");

$_SESSION["student_email"] = $_POST["email"];
$_SESSION["student_name"] = $_POST["name"];
$_SESSION["student_googleclass"] = $_POST["gclass"];

$email = $_SESSION["student_email"];
$name = $_SESSION["student_name"];
$gclass = $_SESSION["student_googleclass"];
  
$roster = array('Student Name' => $name, 'Student Email' => $email);

$heads = array_keys($roster);
$maxs = array();
foreach($heads as $head)
  $maxs[] = count($roster[$head]);
ob_start();
$fp = fopen('php://output', 'w');
fputcsv($fp, $heads);
for($i = 0; $i < max($maxs); $i++)
{   
    $row = array(); 
    foreach($heads as $head)
       $row[] = isset($roster[$head][$i]) ? $roster[$head][$i] : '';
    fputcsv($fp, $row);   
}
fclose($fp);
$roster = ob_get_clean();
var_dump($roster);
?>

EDIT: Here's how I ended up changing by PHP thanks to Felippe Duarte...

<?php
session_start();
header("Content-Type: text/csv");

$_SESSION["student_email"] = $_POST["email"];
$_SESSION["student_name"] = $_POST["name"];
$_SESSION["student_googleclass"] = $_POST["gclass"];

$email = $_SESSION["student_email"];
$name = $_SESSION["student_name"];
$gclass = $_SESSION["student_googleclass"];
  
$roster = array('Student Name' => $name, 'Student Email' => $email);

$heads = array_keys($roster);
$maxs = array();
foreach($heads as $head)
  $maxs[] = count($roster[$head]);
//ob_start();
$fp = fopen('php://output', 'w');
fputcsv($fp, $heads);
for($i = 0; $i < max($maxs); $i++)
{   
    $row = array(); 
    foreach($heads as $head)
       $row[] = isset($roster[$head][$i]) ? $roster[$head][$i] : '';
    fputcsv($fp, $row);   
}
ob_start();

fclose($fp);

//var_dump($roster);
echo $roster;

$roster = ob_get_clean();

?>

Here's an example of the spreadsheet results (I've hidden names and emails for privacy reasons): spreadsheet

So again, how do I just leave "Student Name" (without the quotes). Many thanks!

Upvotes: 0

Views: 162

Answers (1)

Felippe Duarte
Felippe Duarte

Reputation: 15131

Replace var_dump($roster) with echo $roster;.

You already set the header as csv, as long as you format the csv (comma separated values) accordingly, the software will interpret it and display the way you want.

Upvotes: 1

Related Questions