我从可读性中获取xml提要中的数据,并将其插入数据库,然后输出。xml的字符集是UTF-8,我的html页面标题也是UTF-8。我甚至通过文本编辑器将代码保存为UTF-8,我的DB也被设置为utf8_unicode_ci。我搞不懂为什么会这样。
代码:
$xml = simplexml_load_file( "http://readability.com/christopherburton/latest/feed" );
$json = json_encode( $xml );
$array = json_decode( $json,TRUE );
$items = $array['channel']['item'];
$DB = new mysqli('localhost', 'secret', 'secret', 'secret' );
if( $DB->connect_errno ){
print "failed to connect to DB: {$DB->connect_error}";
exit( 1 );
}
$match = "#^(?:[^\?]*\?url=)(https?://)(?:m(?:obile)?\.)?(.*)$#ui";
$replace = '$1$2';
foreach( $items as $item ){
$title = $item['title'];
$url = preg_replace( $match,$replace,$item['link'] );
$title_url[] = array( $title,$url );
$sql_values[] = "('{$DB->real_escape_string( $title )}','{$DB->real_escape_string( $url )}')";
}
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES\n ".implode( "\n,",array_reverse( $sql_values ) );
if( $DB->query( $SQL ) ){
} else {
print "failed to INSERT: [{$DB->errno}] {$DB->error}";
}
$DB->set_charset('utf8');

发布于 2014-01-17 05:35:57
你的问题是放$DB->set_charset('utf8');的地方
在执行查询之前,您需要告诉数据库您在哪个字符集中发送或希望接收数据。
但是,由于查询后有$DB->set_charset('utf8');,所以命令对前面的查询没有任何影响。
如果没有为连接定义字符集,则DMBS使用设置为默认配置的字符集。对于mysql来说,这可能是例如latin1。正因为如此,mysql认为它接收到的数据是用例如latin1编码的,并将其转换为utf8,这就是为什么您会看到这些奇怪的符号。
要解决这个问题,只需确保在传递或希望在$DB->set_charset('utf8');中接收数据的查询之前调用utf8。
对于您的示例,您可以将其放在if( $DB->connect_errno ){}之后,因为在那里成功地建立了连接。
https://stackoverflow.com/questions/21178398
复制相似问题