---
title: "PHP生成utf8格式文件"
author: "javaeyeren"
date: "2009-02-02T16:06:00Z"
tags: []
slug: "php-utf8"
draft: false
lastmod: "2009-02-02T16:06:00Z"
id: 601332
url: "https://javaeyeren.iteye.com/blog/601332"
---

Xml文件格式需要UTF8，而Php默认配置下，用fopen新建的文件都是ASCII格式的，如何让fopen生成新文件时使用UTF8格式呢?  
其实没有特殊技巧，把你要执行的脚本改成utf8格式，fopen生成的新文件在内容包含ASCII字符以外的字符时格式就是utf8格式，内容仅包含ASCII字符仍然是ASCII格式的。

示例：[000-297](http://www.pass4sure.com/000-297.html).Php

[000-297](http://www.pass4sure.com/000-297.html).Php必须为utf8格式

&lt;?Php  
$filename = 'test.txt';  
//$somecontent = "test\\n";  
$somecontent = "test中文\\n";  
if (!$handle = fopen($filename, 'w+')) {  
echo "Cannot open file ($filename)";  
exit;  
}  
if (fwrite($handle, $somecontent) === FALSE) {  
echo "Cannot write to file ($filename)";  
exit;  
}  
echo "Success, wrote ($somecontent) to file ($filename)";  
fclose($handle);  
?&gt;