Read Persian (Unicode chars) text file using php

两盒软妹~` 提交于 2019-12-02 03:52:58

问题


I am reading one Persian text file (using PHP) with the help of below code:

/* 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 file contents :

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

Name file: ����� ���� ��� ��������� (LEARNING NETWORK)


回答1:


The reason you are seeing this is because you are just echoing the contents raw. Your browser will need more information, in order to display the message in its correct form.

The easiest way is to use the snippet below.

/* 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/>';
}

Please note that the header function needs to be executed at the beginning of the output to the browser. So for instance if you have additional data that is displayed prior to this function, you need to move the header statement at the top. Otherwise you will end up with warnings on screen that the headers have already been set.




回答2:


You'll need to make sure that the page where you're displaying the text file has correct encoding.




回答3:


final and best solution is this: use this line under your connect

mysqli_set_charset( $con, 'utf8');

like this:

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

and at the end add this line right under the head tag in your html to make sure your page have utf-8 charset,like this:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

and that's it . you can read formal document here : pph.net charset



来源:https://stackoverflow.com/questions/12588647/read-persian-unicode-chars-text-file-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!