如何在 PHP 中编写制表符分隔的文本文件,并具有正确的编码


How do I write a tab delimited text file in PHP, with proper encoding?

此代码将制表符分隔的 txt 文件从数据库写入目录。我对字符编码有问题,因为它无法获取非英语字符,例如 ñ 、é ,...如何正确编码?我知道我应该使用 UTF-8,但它在我的代码中适合在哪里?这些字符在 db (latin1_swedish_ci) 中看起来正常,但在文件中不正常。谢谢

<?
     @chmod($export_txt, 0777);
    $fe = @fopen($export_txt."/export.txt", "w+");
    if($fe){           
        $somecontent = "";
        $fields_count = 0;           
        // fields headers
        $db->query($sql_view);
        if($row = $db->fetchAssoc()){
            foreach($row as $key => $val){
                if($fields_count++ > 0) $somecontent .= "'t";
                $somecontent .= $key;
            }
        }
        $somecontent .= "'r'n"; 
        $db->query($sql_view);
        while($row = $db->fetchAssoc()){
            $fields_count = 0;
            foreach($row as $key => $val){
                if($fields_count++ > 0) $somecontent .= "'t";
                $somecontent .= $val;                                                                          
            }
            $somecontent .= "'r'n"; 
        }  
        // write some content to the opened file.
        if (fwrite($fe, $somecontent) == FALSE) echo 'file_writing_error'." (export.txt)"; 
        fclose($fe);           
    }
    ?>
fwrite($fe, utf8_encode($somecontent))