0

I have an array like this :

     $data = [
  ["firstname" => "Mary", "lastname" => "Johnson", "age" => 25],
   ["firstname" => "Amanda", "lastname" => "Miller", "age" => 18],
   ["firstname" => "James", "lastname" => "Brown", "age" => 31],
   ["firstname" => "Patricia", "lastname" => "Williams", "age" => 7],
   ["firstname" => "Michael", "lastname" => "Davis", "age" => 43],
   ["firstname" => "Sarah", "lastname" => "Miller", "age" => 24],
   ["firstname" => "Patrick", "lastname" => "Miller", "age" => 27]
 ];

I want to create an downloadable csv file from this array in php. like this:

enter image description here

unicode utf-8 is important too.

I have found the solution:

<?PHP

 function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) ||          preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
    $str = "'$str";
  }
  if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  $str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');

}

// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv; charset=UTF-16LE");

$out = fopen("php://output", 'w');

$flag = false;
foreach ($data as $row) {
   if(!$flag) {
    // display field/column names as first row
    fputcsv($out, array_keys($row), ',', '"');
    $flag = true;
  }
  array_walk($row, __NAMESPACE__ . '\cleanData');
   fputcsv($out, array_values($row), ',', '"');
}

fclose($out);
exit;
 ?>

it works and creates .csv file but it show Persian Chars unreadable.

3
  • This is quite simple, so what have you tried? Commented Jan 12, 2017 at 23:00
  • That screenshot does not show a CSV file but a spreadsheet application. Commented Jan 12, 2017 at 23:00
  • You don't need to create a physical file for this. You simply send a mime type header for the CSV format and then the data itself. That's all the magic. Commented Jan 12, 2017 at 23:01

1 Answer 1

0

Use http://php.net/manual/en/function.fputcsv.php

$fp = fopen('php://output', 'w');
fputcsv($fp, array_keys($data[0]));

foreach ($data as $row) { 
    fputcsv($fp, array_values($row));
}

fclose($fp);

Converting the array to UTF8 can be done using something like

$dataUTF8 = array_map("utf8_encode", $data);
Sign up to request clarification or add additional context in comments.

4 Comments

no need to create an actual file $fp = fopen('php://output', 'w');
you are right. I have updated the answer. It will output the csv content to the browser.
It does not answer all the question either, however the Sup does.
can you tell me what does not work? Does it give an error?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.