【发布时间】:2014-02-06 08:10:38
【问题描述】:
我从可读性获取 xml 提要中的数据并将其插入数据库,然后输出。 xml 提要的字符集是UTF-8,我的html 页面标题也是UTF-8。我什至通过我的文本编辑器将代码保存为UTF-8,我的数据库也设置为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');
【问题讨论】:
-
您在查询之后设置
$DB->set_charset('utf8');,但您需要在查询之前设置它 -
@t.niese 有人为我做了这个,所以我不知道该放在哪里。我应该在连接后放置它吗?
-
@t.niese 我把它放在 $SQL 之前,它起作用了。尴尬的问题。你能把你的建议变成答案吗?