我解析XML文件從URL(在下面的代碼中),使用file_get_contents()函數和simpleXML,插入數據到表中,我做得很好,但我有問題編碼(俄語單詞)我得到這個 - >РСРμРЅРšРіРРССРРССС;文件和數據庫編碼設置爲utf-8;xml到php和解析編碼錯誤
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";
}
}
在瀏覽器view-source中看到的源代碼是'windows-1251',你的db是'utf-8' ...希望在db中插入xml數據之前先運行適當的轉換。 –