使用php读取波斯语(Unicode字符)文本文件

时间:2012-09-25 18:05:48

标签: php utf-8 fopen fread

我正在使用以下代码阅读一个波斯语文本文件(使用PHP):

/* Reading the file name and the book (UTF-8) */
if(file_exists($SourceDirectoryFile))
{
        $NameBook  = "name.txt";
        $AboutBook = "about.txt";

        $myFile = "Computer-Technolgy/2 ($i)/".$NameBook;
        $fh = fopen($myFile, 'r');
        $theData = fread($fh, filesize($myFile));
        fclose($fh);
        echo 'Name file: '. $theData.'<hr/>';
}

name.txt文件内容:

آموزش شبكه هاي کامپيوتري (LEARNING NETWORK)

名称文件: (学习网络)

3 个答案:

答案 0 :(得分:5)

您看到这个的原因是因为您只是回显原始内容。您的浏览器需要更多信息,以便以正确的形式显示消息。

最简单的方法是使用下面的代码段。

/* Reading the file name and the book (UTF-8) */
if (file_exists($SourceDirectoryFile))
{

    $NameBook  = "name.txt";
    $AboutBook = "about.txt";

    // Using file_get_contents instead. Less code
    $myFile   = "Computer-Technolgy/2 ($i)/" . $NameBook;
    $contents = file_get_contents($myFile);

    // I want my browser to display UTF-8 characters
    header('Content-Type: text/html; charset=UTF-8');
    echo 'Name file: ' .  $contents . '<hr/>';
}

请注意,header功能需要在输出开始时执行到浏览器。因此,例如,如果您在此函数之前显示了其他数据,则需要在顶部移动header语句。否则,您最终会在屏幕上显示已设置标题的警告。

答案 1 :(得分:0)

您需要确保显示文本文件的页面为correct encoding

答案 2 :(得分:0)

最终和最佳解决方案是: 在你的连接

下使用这一行
var biosample= (from a in db.Biosample
                 select a);
if (catalognbr != -1)
{ 
    biosample = biosample.Where (a => a.Catalog_nbr ==catalognbr);
}                 
像这样:

mysqli_set_charset( $con, 'utf8');

并在最后在html的head标签下添加此行,以确保您的页面具有utf-8字符集,如下所示:

$con = mysqli_connect("localhost","root","amirahmad","shoutit");
mysqli_set_charset( $con, 'utf8');

就是这样。你可以在这里阅读正式文件:pph.net charset