我有一个PHP脚本,它获取XML,选择一些数据,并将它们插入我的数据库(MySQL)。我的所有字段都是utf8_bin。此XML是ISO-8859-1,并且无法更改此,因为是另一个将其发送给我的站点。
示例:我的数据库中的字符串“NGContábil”设置为“NGContrábil”。这是我的剧本:
<?php
header('Content-Type: text/html; charset=utf-8');
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
include '/PagSeguroLibrary/PagSeguroLibrary.php';
include '/PagSeguroLibrary/domain/PagSeguroAccountCredentials.class.php';
include 'conexao.php';
include 'alias_array.php';
include 'retorna_cpf.php';
$conexao = ConectaBD::get_instance();
$conexao->conectar_pronto();
$conexao->BD_pronto();
//(...)
$xml = simplexml_load_file('arquivo.xml');
if($xml === null)
$xml = simplexml_load_string($resposta_transacao);
$status = $xml->status;
$nome = $xml->sender->name;
$email = $xml->sender->email;
$codigo = $xml->code;
$vetor = $xml->items->item;
$cpf = retorna_cpf($email);
foreach($vetor as $v)
{
$nome_produto = $v->description;
if($nome_produto != 'frete')
{
//Retorna o id do produto a partir da descrição
$result = mysql_query('SELECT id_product
FROM ps_product_lang
WHERE name = "'.$nome_produto.'"');
$array = Array();
while($row = mysql_fetch_alias_array($result))
{
foreach($row as $linha)
array_push($array, $linha);
}
mysql_query('INSERT INTO pagamento(Status, Nome, Email, CPF, idproduto, Codigo, Inscrito, id, Enviado, NomeProduto)
VALUES ("'.$status.'", "'.$nome.'", "'.$email.'", "'.$cpf.'", "'.$array[0].'", "'.$codigo.'", 0, null, 0, "'.$nome_produto.'")');
}
}
fclose($arquivo);
unlink('arquivo.xml');
?>
感谢您的回答!
答案 0 :(得分:2)
你忽略了一点点细微差别:
mysql_query("SET NAMES 'utf8'");
不是为了进行正确的编码而必须强制转换的魔法咒语,但实际上是一个SQL查询,需要在实际用于运行的同一实例中运行 SQL查询。
因此,如果您使用ConectaBD :: get_instance()连接到您的mysql数据库;您必须在之后运行SET NAMES utf8
查询,而不是之前。
我不知道为什么,但添加utf8_decode()解决了问题
我知道。
simplexml
的输出始终 utf-8
虽然如上所述,您不会将客户端连接设置为utf8
因此,它仍然是默认latin1
使用(非常无用)utf8_decode()调用您将utf-8
数据转换回latin1
,从而将其正确存储到数据库中。
答案 1 :(得分:1)
这可以解决您的问题:
...
$xml = simplexml_load_file('arquivo.xml');
$xml = iconv('ISO-8859-1', 'UTF-8', $xml);
...