0

1[This is the output] Trying to export SQL data as excel file by looping the array but failed to export the leading 0 of data.

I had tried to place single quote in the implode but still not working

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$user_query = mysqli_query($conn,$sql);
//echo $user_query;
// Write data to file
$flag = false;
while ($row = mysqli_fetch_assoc($user_query)) {
    if (!$flag) {
        // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\r\n";
        $flag = true;
    }
        echo implode("\t", =array_values($row)) . "\r\n";

}

Expect to implode with "\t'" with the single quote but still failed to export the leading 0

yesman333
  • 35
  • 5
  • could you show `$row` output? What you have in `$row` – PHP Ninja Aug 01 '19 at 04:25
  • 1
    Stop the messing around with `implode`, and use `fputcsv` to begin with. (For an example how to use the latter for a direct download, instead of writing to an actual file, see https://stackoverflow.com/a/16251849/10283047) – misorude Aug 01 '19 at 07:38
  • @misorude I don't think CSV is expected. He's using XLS headers. – Bram Verstraten Aug 01 '19 at 08:22
  • @BramVerstraten _“He's using XLS headers”_ - yeah, but the actual data format is still quite CSV-like. You’re not limited to creating “classic” CSV data with that function, it can take any character for delimiter and enclosure. (It doesn’t wrap values with a leading 0 into quotes though - maybe I’d just use a quick `array_walk` for that.) – misorude Aug 01 '19 at 08:26
  • show the content of `array_values($row)` or one generated line. – Ibu Aug 01 '19 at 23:57

1 Answers1

1

Change your implode like this so that each value is quoted in single quotes:

echo "'".implode("'\t'", array_values($row)) . "'\r\n";

UPDATE

Quoting only fields with a leading zero:

echo implode("\t", array_map('leadZero', $row))."\r\n";

function leadZero($element)
{
  return substr(trim($element),0,1) === "0" ? "'".$element."'" : $element;
}
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26