0

I'm having a problem with file_get_contents and fwrite.

To get a script to work I have to print content from an external URL into a html file.

I'm using this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<?php
$url = 'http://www.vasttrafik.se/nasta-tur-fullskarm/?externalid=9021014005135000';
$content = file_get_contents($url);  
echo $content; // Actually writes out correct

$myFile = "response.php";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $content); // Doesn't write out correct ???
fclose($fh);
?>

</body>
</html>

When I echo out the file_get_contents, the HTML shows up nicely (with the Swedish special characters: åäö)

However.. The file "response.php" shows bad characters instead of åäö.

Any ideas? Does the fwrite use another encoding? Thanks!

UPDATE! Solved with this:

$content = "\xEF\xBB\xBF";
$content .= utf8_encode(file_get_contents($url));  
Stichy
  • 1,497
  • 3
  • 16
  • 27
  • http://stackoverflow.com/questions/13932519/utf-8-characters-in-fwrite – aborted Dec 10 '13 at 12:18
  • How exactly are you checking the results in that file? – deceze Dec 10 '13 at 12:29
  • @Dugi: Didn't help :/ deceze: When I echo $content, it works. But when I surf in to "response.php" the letters: "åäö" is wierd.. And Yes, the file response.php is updated when I run this script – Stichy Dec 10 '13 at 12:49

1 Answers1

2

SOLVED!

I needed to ad a BOM (Byte Order Mark) AND utf8_encode.

Like this:

$content = "\xEF\xBB\xBF";
$content .= utf8_encode(file_get_contents($url));  
Stichy
  • 1,497
  • 3
  • 16
  • 27
  • 1
    What you have done is make the output compatible with whatever you are using to read the file - the data in the file was never written incorrectly. – symcbean Dec 10 '13 at 13:13