---
title: "fwrite 与文件编码"
author: "muyu"
date: "2009-08-26T15:31:14Z"
tags: []
categories: ["编程语言"]
slug: "fwrite"
draft: false
lastmod: "2009-08-26T15:31:14Z"
id: 457987
url: "https://muyu.iteye.com/blog/457987"
---

fwrite函数可以把字符串写入文件，文件最终的编码取决于要写入的字符串编码。如果字符串是utf-8，那么最终的文件就是utf-8编码；如果字符串是gb2312，那么最终的文件就是gb2312.

 

下面的示例代码，演示了重复打开、转换编码、保存同一个文件的过程，每执行一次操作，用记事本打开文件（a.txt），查看它的编码是否在utf-8和gb2312之间变换。

 

```
/**
 * 判断字符串是否为utf-8格式
 *
 * @param string $string
 * @return 0或1
 */
function is_utf8($string) {
    return preg_match('%^(?:
    [\x09\x0A\x0D\x20-\x7E] # ASCII
    | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
    | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
    | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
    | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
    | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
    | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
    )*$%xs', $string);
}

/**
 * 读文件
 *
 * @param string $source
 * @return string / false
 */
function fileToStr($source) {
	if (file_exists($source)) {
	    $str = file_get_contents($source);
	    return $str;
	} else {
	    return false;
	}
}

/*----------诸函数----------*/
/**
 * 用字符串覆盖指定的文件
 *
 * @param string $destination
 * @param string $contents
 */
function saveFile($destination, $contents) {
	$tp = @fopen($destination, 'wb');
	fwrite($tp, $contents);
	fclose($tp);
}


//测试程序开始
$str = fileToStr('a.txt');
if(is_utf8($str)) {
  $str = iconv('utf-8', 'gb2312', $str);
} else {
  $str = iconv('gb2312', 'utf-8', $str);
}

echo is_utf8($str);
echo "\n";
saveFile('a.txt', $str); //每打开、再保存一次a.txt，它的编码将变化一次。
```