2013-12-10 37 views
0

我遇到了file_get_contents和fwrite的问题。Php - fwrite坏字符

为了让脚本工作,我必须将内容从外部URL打印到html文件中。

我使用这个代码:

<!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> 

当我回声出的file_get_contents,在HTML很好地显示出来(与瑞典特殊字符:AAO)

但是..文件“response.php”显示不好的字符而不是åäö。

任何想法? fwrite是否使用另一种编码? 谢谢!

更新! 解决这个:

$content = "\xEF\xBB\xBF"; 
$content .= utf8_encode(file_get_contents($url)); 
+0

http://stackoverflow.com/questions/13932519/utf-8-characters-in-fwrite – Aborted

+0

究竟你是如何检查该文件中的结果吗? – deceze

+0

@Dugi:没有帮助:/ deceze:当我回显$内容时,它可以工作。但是当我冲浪到“response.php”时,字母:“åäö”很奇怪。是的,当我运行这个脚本时,文件response.php被更新 – Stichy

回答

1

解决了!

我需要添加BOM(字节顺序标记)和utf8_encode。

像这样:

$content = "\xEF\xBB\xBF"; 
$content .= utf8_encode(file_get_contents($url)); 
+1

你所做的是使输出与你所用于读取文件 - 文件中的数据从未被错误地写入。 – symcbean