Question

SO i have been trying to create a simple csv file as code below but the csv file not created properly. It contained the html text that are in my .php file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>CVS File</title>
</head>

<body>

<table width="370" border="0" cellspacing="0" cellpadding="0">
    <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <tr>
        <td><h1> Ultracom </h1></td>
        <td align="right" valign="middle">
          <input name="csv" type="file" id="csv" />
          <input type="submit" id="btnsubmit" name="btnsubmit" value="Submit" />
        </td>
    </tr>   
    <tr>
        <td><input type="submit" id="btnedit" name="btnedit" value="Edit" /></td>
        <td></td>
    </tr>
    <tr>
        <td><input type="submit" id="btnupdate" name="btnupdate" value="Update" /></td>
        <td><input type="submit" id="btncancel" name="btncancel" value="Cancel" /></td>
    </tr>
    </form>
</table>

<?php
if (isset($_POST['btnupdate'])) {

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=edited.csv');
$file = fopen("edited.csv","w");

$row = 2;
$a = "a";
$b = "b";

for ($r=0; $r < $row; $r++) {
    $rows[$r] = $a.",".$b;
}

foreach ($rows as $details) {
  fputcsv($file,explode(',',$details));
}

fclose($file);
}
?>

Is there anything wrong with my code? My code seems like mostly the same like other code to create csv file that i found so far on google.

No correct solution

OTHER TIPS

What a waste...

for ($r=0; $r < $row; $r++) {
    $rows[$r] = array($a, $b); // build an array of arrays...
}

foreach($rows as $details) {
   fputcsv($file, $details);  // use the array directly
}

There is ZERO point in building a string from distinct bits of data, just to explode that single string back into distinct bits of data later on.

As far as the rest of the code goes, if you're intending to download that csv to the client browser, you never actually output the csv once it's built. You'd need

...
fclose($file);
readfile($file); // dump to client
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top