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

Sae*_*eid 2 php fopen utf-8 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/>';
}
Run Code Online (Sandbox Code Playgroud)

name.txt文件内容:

????? ???? ??? ????????? (LEARNING NETWORK)
Run Code Online (Sandbox Code Playgroud)

姓名档案: (学习网络)

Nik*_*los 6

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

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

/* 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/>';
}
Run Code Online (Sandbox Code Playgroud)

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