douhui9631 2013-06-27 10: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 11: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条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP