Page 1 of 1

Encoding MSSQL fields to UTF-8 + JSON issue

Posted: Thu May 07, 2009 3:08 pm
by joaocunha
This is my first post, so hi to everyone.

I'm starting to use ExtJS + PHP5 + MSSQL. The first one is reading a JSON provided by a PHP page, that selects data from a MSSQL database. JSON supports UTF-8 encoded strings only, and I'm having a bad time trying to figure out what to do.

The only workaround I found is:

Code: Select all

 
    $return = mssql_query($query, $dbHandle);
    
    $count = 0;
    while ($db = mssql_fetch_array($return)){
        $dados[$count]->cd_responsavel = $db['cd_responsavel'];
        $dados[$count]->cd_tipo = $db['cd_tipo'];
        $dados[$count]->tx_nome = utf8_encode($db['tx_nome']);
        $dados[$count]->tx_email = utf8_encode($db['tx_email']);
        $dados[$count]->tx_grupos = utf8_encode($db['tx_grupos']);
        $dados[$count]->tx_usuarioweb = utf8_encode($db['tx_usuarioweb']);
        $dados[$count]->ck_ativo = $db['ck_ativo'];
        $dados[$count]->dt_nascimento = $db['dt_nascimento'];
        $dados[$count]->tx_apelido = utf8_encode($db['tx_apelido']);
        $dados[$count]->tx_sexo = utf8_encode($db['tx_sexo']);
        $count++;
    }
    
    echo '{"total":"100 (example)","results":' . json_encode($dados) . '}';
 
Obviously not the best solution, since it will require a (manual!) utf8_encode call at every single string field of any query. I did tried to get the data already UTF-8'ed from the database, but no clue (it's not MySQL, so can't use 'SET ...').

I get exactly the same result with the code below, but unencoded (so, string is truncated in the accents):

Code: Select all

 
    while($db = mssql_fetch_object($retorno)) {
        $dados[] = $db;
    }
    ...
 
To know:
- All system is using UTF-8 encoding, including the file itself (page.php);
- I'm already using the charset header especifying UTF-8;
- Don't really know how the MSSQL is encoded (so guessing it's ISO-8859-1);

Is there something I'm missing? I can't change the way database is encoded by default, because it's used by external systems. If there's a simple way of doing this, avoiding "reloops" or messing with the query, please let me know.

Huge thanks by now, hope you understand my english (and my problem, of course).

Re: Encoding MSSQL fields to UTF-8 + JSON issue

Posted: Fri May 08, 2009 2:50 pm
by joaocunha
I can solve this relooping the array in order to utf8_encode the data, but that's not good also. Struggling with PHP syntax to set the encode in the first loop, so the array would be joined just right and in the first iteration. But still have no clues.

Re: Encoding MSSQL fields to UTF-8 + JSON issue

Posted: Tue May 12, 2009 7:45 am
by joaocunha
Nothing? I can give more details if needed...