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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog