Search code examples
phpfilearabic

php file_get_contents Arabic Characters


Hello I have a problem in my PHP code : I need to open a txt file using file_get_contents, the directory to the txt file contains arabic Characters my code:

$URLX = "C:/server files/BN/public_html" ; 
$BookName = "الإضافةإلىمفاوضةمالكحسون" ; 
$eachChapiter[$x] = "مالكمالكحسون" ; 

$content = file_get_contents($URLX."/".$BookName."/".str_replace(' ', '', $eachChapiter[$x]).".txt"); 

the error output :

WARNING: FILE_GET_CONTENTS(C:/SERVER FILES/BN/PUBLIC_HTML/الإضافةإلىمفاوضةمالكحسون/مالكمالكحسون.TXT): FAILED TO OPEN STREAM: NO SUCH FILE OR DIRECTORY IN C:\XAMPP\HTDOCS\LIBRARY\SEARCH\SEARCH.PHP ON LINE 30

NOTICE: UNDEFINED OFFSET: 1 IN C:\XAMPP\HTDOCS\LIBRARY\SEARCH\SEARCH.PHP ON LINE 38

Solution

  • Thanks @Mike for helping me correct the answer. So As per the question and OP's OS it seems that you(OP) are encountering a variant of this error.

    And as discussed on that link, you can use the following code to detect the file name encoding

    ...    
    
    $final_url = $URLX."/".$BookName."/".str_replace(' ', '', $eachChapiter[$x]);
    
    mb_detect_encoding($final_url, 'UTF-8', true)) ? utf8_decode($final_url) : $final_url;
    $content = file_get_contents($final_url).".txt");
    

    Remember that this code will create problems(again discussed on that link) on a linux server. So if you are using Linux production environment then you can apply the solution suggested there.