0

你好,我有这段代码可以将我的数据从.xls 导出,但我的编码有问题,这是我的代码

<?php
header("Content-Type: text/plain;charset=UTF-8");


function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
  if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

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

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel; charset=UTF-8");


$data = array(
array('firstname'   =>'Name', 'last_name'   => 'Last Name', 'age'   => '25'),
array('firstname'   =>'name 2', 'last_name' => 'Last Name 2', 'age' => '27')
);


$flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    }
       array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
  }
  exit;
?>

我尝试了编码 iso-8859-7、windows-1253 和 UTF-8,我想用希腊字符导出我的所有数据都是 UTF-8。谢谢你的帮助

4

1 回答 1

0
<?php
include('connect.php');
header("Content-Type: text/plain; charset=UTF-8");


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) . '"';

  }

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

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

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

$flag = false;
  $result = mysql_query("SELECT * FROM categories ORDER BY id") or die('Query failed!');
  while(false !== ($row = mysql_fetch_assoc($result))) {
    if(!$flag) {
      // display field/column names as first row
      fputcsv($out, array_keys($row), ',', '"');
      $flag = true;
    }
    array_walk($row, 'cleanData');
    fputcsv($out, array_values($row), ',', '"');
  }

  fclose($out);
  exit;
?>

我更改了我的代码,在文本编辑器中我可以看到我的字符很好,并且编码是希腊语,但是当我在 microsoft excel 中打开时,它是不可读的

于 2013-07-10T09:26:00.333 回答