Paulo Hgo
Paulo Hgo

Reputation: 860

Encoding issues with PHP

I have been searching and trying for hours and can't seem to find anything that actually solves my problem. I'm calling a PHP function that grabs content using the Google translate API and I'm passing a string to be translated. There are quite a few instances where the encoding is affected but I've done this before and it worked fine as far as I can remember.

Here's the code that calls that function:

$name = utf8_encode(mt($name));

And here's the actual function:

function mt($text) {

    $apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    $url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=es';
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($handle);
    echo curl_error($handle);
    $responseDecoded = json_decode($response, true);
    $responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);      //Fetch the HTTP response code
    curl_close($handle);

    if($responseCode != 200) {
        $resultxt = 'failed!';
        return $resultxt;
    }
    else {
        $resultxt = $responseDecoded['data']['translations'][0]['translatedText'];
        return utf8_decode($resultxt);  //return($resultxt) won't work either
    }
}

What I end up getting is garbled characters for any accentuated character, like Guía del desarrollador de XML I've tried all combinations of encoding/decoding and I just can't get it to work...

Upvotes: 1

Views: 92

Answers (1)

Gonz
Gonz

Reputation: 1219

I had this kind of issues before, what I can tell you to try is:

  1. In the <head> tag try to add:

<meta http-equiv=”Content-type” content=”text/html; charset=utf-8″ />

  1. Try to add it in the PHP header:

header(“Content-Type: text/html;charset=utf-8”);

  1. Check the encoding of your file, for example in the Notepad ++

Encoding > UTF-8 without BOM

  1. Setting charset in the .htaccess

AddDefaultCharset utf-8

  1. As you said you are reading files from the users you can use this function: mb-convert-encoding to check for the encoding, and if it's different from UTF-8 convert it. Try this:

Upvotes: 1

Related Questions