0

I haven't done PHP for a while so I apologize in advance if it's something simple.

I'm migrating a PHP-based site to a shared web hosting and there's an issue with the way it outputs HTML markup. Let's consider the following code snippet that reads HTML from a file on the server and outputs it to the web browser:

$handle = @fopen($file_name, "rb");

$str = @fread($handle, filesize($file_name));
fclose($handle);

print $str;

For some reason it replaces some characters on the page. Like it puts that character instead of an apostrophe:

enter image description here

while it looked normal when the exact same code ran from a previous web hosting server:

enter image description here

Any idea what am I missing here?

c00000fd
  • 20,994
  • 29
  • 177
  • 400
  • 7
    It's an encoding issue. Have a read here http://stackoverflow.com/questions/279170/utf-8-all-the-way-through - Definitely the type of quote used. You can also replace it if you can with `str_replace()`. – Funk Forty Niner Mar 28 '16 at 17:47
  • Have you tried adding a meta charset tag in the head? ``. – Dave Chen Mar 28 '16 at 17:55

1 Answers1

1

Thats an encode error, if your text have some especial characters, some encode types doesn't recognize it correctly..

Try put your header to recognize utf-8 encode, add this (inside you php tag, at the beginning!) to your code

header('Content-Type: text/html; charset=utf-8');
file_put_contents($myFile, "\xEF\xBB\xBF".  $content); 

And add this meta tag inside your html head

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

UPD:

I've done some research on php reference(http://php.net/manual/en/function.fopen.php#104325), and i found something! Try use this php function to solve your problem:

<?php 
function utf8_fopen_read($fileName) { 
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
    $handle=fopen("php://memory", "rw"); 
    fwrite($handle, $fc); 
    fseek($handle, 0); 
    return $handle; 
} 
?> 

Example of how to use:

Example usage: 

<?php 
$fh = utf8_fopen_read($filename); 
while (($data = fgetcsv($fh, 1000, ",")) !== false) { 
    foreach ($data as $value) { 
        echo $value . "<br />\n"; 
    } 
} 
?> 

Hope it helps!

Han Arantes
  • 775
  • 1
  • 7
  • 19
  • Thanks. I tried both. I actually had an html meta tag configured for utf-8. But still, no change. What else am I missing? – c00000fd Mar 28 '16 at 18:22
  • @c00000fd check my upd – Han Arantes Mar 28 '16 at 18:36
  • Thank you. Your `utf8_fopen_read` hack worked. Hate php! Every time I try to deal with it, they either depreciate some previously working code, or you have to jump over your head to make it work with the simplest of stuff... – c00000fd Mar 28 '16 at 23:21