Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Persian (Unicode chars) text file using php

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)

like image 661
Saeid Avatar asked Mar 13 '26 19:03

Saeid


1 Answers

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.

like image 55
Nikolaos Dimopoulos Avatar answered Mar 15 '26 09:03

Nikolaos Dimopoulos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!