2013-03-12 202 views
0

我有一个PHP脚本,它获取XML,选择一些数据并将它们插入到我的数据库(MySQL)中。我所有的字段都是utf8_bin。这个XML是ISO-8859-1,不能改变这个,因为是另一个网站发送给我。插入数据库时​​字符损坏

例如:字符串“NGContábil”在我的数据库中设置为“NGContá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

你能粘贴XML中的第几行吗? – Sjoerd 2013-03-12 14:29:36

+0

它是'utf8'还是'utf-8'? – EmCo 2013-03-12 14:30:09

+0

我也有同样的问题..使用mysql_set_charset()解决了我的问题... http://php.net/manual/en/function.mysql-set-charset.php看看 – alwaysLearn 2013-03-12 14:33:28

回答

2

你忽略只是一个小的细微差别:
mysql_query("SET NAMES 'utf8'");是不是一个神奇的法术有为了使正确的编码定投,但实际上是一个SQL查询,需要运行与您实际用于运行SQL查询的实例相同。因此,如果你使用ConectaBD :: get_instance()连接到你的mysql数据库,那么你可以使用ConectaBD :: get_instance()来连接你的mysql数据库。你必须运行SET NAMES utf8查询之后那个调用,而不是之前。

我不知道为什么,但添加utf8_decode()解决了这个问题

我知道。
simplexml的输出是总是 utf-8。
虽然,正如我上面指出的那样,您不会将客户端连接设置为utf8
因此,它仍然是默认latin1
随着(相当无用)utf8_decode()调用你您铸造utf-8数据回latin1因此它正确地存储到数据库中。

+0

大!这解决了我的问题。非常感谢你! – 2013-03-12 15:19:07

1

这应该解决您的问题:

... 
$xml = simplexml_load_file('arquivo.xml'); 
$xml = iconv('ISO-8859-1', 'UTF-8', $xml); 
...