转换字符串编码

做文章采集的时候,遇到了不同网站的字符编码不同的问题,于是写了一个简单的字符转换函数

 

<?php
/*
转换字符串编码
*/
function convert($str, $from = 'utf-8', $to = 'gb2312') {
if(!$str) return false;
if(!is_string($str))return false;
$from = strtolower($from);
$to = strtolower($to);
$from = str_replace('gbk', 'gb2312', $from);
$to = str_replace('gbk', 'gb2312', $to);
$from = str_replace('utf8', 'utf-8', $from);
$to = str_replace('utf8', 'utf-8', $to);
if($from == $to) return $str;
$tmp = array();
if(function_exists('iconv')) {
return iconv($from, $to."//IGNORE", $str);
} else if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($str, $to, $from);
} else {
return false;
}
}
?>

  

posted @ 2015-07-03 17:10  个人笔记  阅读(247)  评论(0编辑  收藏  举报