0

我在这个网站上搜索了很多答案,但没有一个对我有用。我正在尝试使用 PHP simplexml_load_string 解析以下 XML。

我的 XML 是:

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

当我使用 print_r 打印它时,结果如下所示:

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

当我使用 ini_set('default_charset', 'UTF-8') 或 header('Content-Type: text/html; charset=utf-8') 结果是:

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

但是,当我尝试在数据库(MySQL)中使用 PHP(标头设置为 utf8)插入国家/地区值时,它以 Großbritannien 的形式插入。我的表字符集是 UTF8,列的排序规则是 utf8_unicode_ci。但是,当我直接将国家/地区值插入表中(使用 phpMyAdmin 或终端)时,它会正确插入。

我想知道为什么没有从我的 PHP 解析页面正确插入国家值。

我的 PHP 示例代码如下:

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

请帮帮我。提前谢谢大家。

4

2 回答 2

1

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)

于 2013-06-27T11:31:16.563 回答
1

在插入查询上方插入此内容

mysql_query('SET NAMES utf8');

AS @deceze 指出最好使用

mysql_set_charset('utf8');
于 2013-06-27T11:21:12.450 回答