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.

Hamid hp
  • 9
  • 3

1 Answers1

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);
cornelb
  • 6,046
  • 3
  • 19
  • 30