我正在从url(在下面的代码中(解析xml文件,使用file_get_contents((函数和simpleXML将数据插入表中,我做得很好,但是我在编码(俄语单词(方面有问题,我得到这个 ->Р§РμСЂРЅРЅЅѕРіРѕСЁСЏ; 文件和数据库编码设置为 utf-8;
require_once 'mysql_connect.php';
/**
*
*
*/
error_reporting(E_ALL);
$sql = "CREATE TABLE IF NOT EXISTS `db_countries` (
`id` int(11) unsigned NOT NULL auto_increment,
`countrykey` varchar(255) NOT NULL default '',
`countryname` varchar(255) NOT NULL default '',
`countrynamelat` varchar(500) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
mysql_query($sql);
$data = file_get_contents("http://www2.turtess-online.com.ua/export/dictionary/countries/");
$xml = new SimpleXMLElement($data);
echo $xml->body->dictionary->element["countryName"];
foreach ($xml->body->dictionary->element as $element) {
$countryname = mysql_real_escape_string($element["countryName"]);
$countrynamelat = mysql_real_escape_string($element["countryNameLat"]);
$countrykey = $element["countryKey"];
if ($countrykey) {
$q = $insert = 'INSERT INTO db_countries (countrykey, countryname, countrynamelat) VALUES ("' . $countrykey . '", "' . $countryname . '", "' . $countrynamelat . '")';
mysql_query($q);
} else {
echo "not valid key of country";
}
}
确保也插入 Unicode 内容,数据库字符集没有进行任何"自动"转换。
作为替代方案,我建议utf8_encode($countryname)
如下:
if ($countrykey) {
$q = $insert = 'INSERT INTO db_countries (countrykey, countryname, countrynamelat) VALUES ("' . $countrykey . '", "' . cp1251_to_utf8($countryname) . '", "' . $countrynamelat . '")';
mysql_query($q);
} else {
echo "not valid key of country";
}
更新:实际上,XML源文件显示Windows 1251字符集
更新(2(:我针对这个漂亮的小函数测试了代码,它终于可以工作了:)
function cp1251_to_utf8($s)
{
if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
{
$c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
for($i=0; $i<strlen($s); $i++)
{
$c=ord($s[$i]);
if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
elseif ($c>239) $t.=$c209.chr($c-112);
elseif ($c==184) $t.=$c209.$c209;
elseif ($c==168) $t.=$c208.$c129;
else $t.=$s[$i];
}
return $t;
}
else
{
return $s;
}
}
功劳归于马丁·彼得罗夫