douhui9631 2013-06-27 02:56
浏览 71
已采纳

UTF-8特殊字符作为奇怪的字符插入表中[重复]

This question already has an answer here:

I searched in this site there were lots of answers but none of them are working for me. I am trying to parse the below XML using PHP simplexml_load_string.

My XML is:

<?xml version="1.0" encoding="utf-8"?>
<address>
<name>Peter</name>
<country>Großbritannien</country>
</address>

When I print it using print_r the result is showing as below:

SimpleXMLElement Object
(
    [name] => Peter
    [country] => Großbritannien
 )

and when I use ini_set('default_charset', 'UTF-8') or header('Content-Type: text/html; charset=utf-8') the result is:

SimpleXMLElement Object
(
    [name] => Peter
    [country] => Großbritannien
)

But When I try to insert the country value using PHP (with the header set as utf8) in the database (MySQL) then its inserting as Großbritannien. My tables character-set is UTF8 and collation of the column is utf8_unicode_ci. However when I directly insert the country value into the table(using phpMyAdmin or terminal) then its inserting properly.

I would like to know why the country value is not inserting properly from my PHP parsing page.

My PHP sample code is below:

$notificationXml  = simplexml_load_string($xml); 
$con = $notificationXml->country;
mysql_query("INSERT INTO test_1 (con) values ('$con')");

Please help me out. Thanking you all in advance.

</div>

展开全部

  • 写回答

2条回答 默认 最新

  • dph58509 2013-06-27 03:31
    关注

    a) the extension providing the mysql_* functions is marked as deprecated. Better to start with pdo_mysql or mysqli
    b) You have to take care of the connection charset, i.e. essentially the charset the MySQL server expects the client to use when sending/receiving data. Avoid using something like SET NAMES ... as it would leave the client side mysql library in the dark about the new charset/encoding rules, so some character handling may not work as intended which may even lead to security related issues. Use the dedicated client side mechanism for changing the charset instead. For mysql_* that would be mysql_set_charset()., for mysqli_* mysqli::set_charset() and for pdo you should put that information into the dsn like

    $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8')
    

    (and use a php version >= 5.3.6)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部