0

I'm using Cloud Translate API to translate lots of strings but sometimes I get back results like this:

votre \u00e9v\u00e9nement une exp\u00e9rience unique.

I have to use search and replace inside my IDE to fix it but I was wondering if there's a way to replace these weird characters for their real characers using PHP?

EDIT:

This is my code to translate right now:


$htmlString = '';
        $source = 'es';
        $target = 'fr';

        $key = 'dkfvñkdmgbñmb-8';

        $translate = new TranslateClient([
            'key' => $key
        ]);

        //$trans = new GoogleTranslate();

        $newArray = [];
        $json = File::get(base_path() . '/resources/lang/español.json');
        $array = json_decode($json, true);

        foreach ($array as $key => $value) 
        {
            //$result = $trans->translate($source, $target, $value);

            $text_translated = $translate->translate($value, [
                'source' => $source,
                'target' => $target,
                'format' => 'text'
            ])['text'];

            $string = $text_translated;

            $string = preg_replace('/%u([0-9A-F]+)/', '&#x$1;', $string);

            $newArray[$key] = html_entity_decode($string);
            //sleep(1);
            usleep( 500000 );
        }

        $fileName = '/temp/translated-'.rand(1,1000).'.json';

        Storage::disk('public')->put($fileName, json_encode($newArray));
gabogabans
  • 3,035
  • 5
  • 33
  • 81
  • The real answer is in the comments of the accepted answer of the linked duplicate. There's a lot of escaping that needs to be done in the preg_replace. – aynber Apr 11 '23 at 16:30
  • 1
    Are you looking at a JSON response with your eyeballs instead of using `json_decode()`? – Sammitch Apr 11 '23 at 17:23
  • those are escaped unicode characters. use the `JSON_UNESCAPED_UNICODE` flag when encoding/decoding json to avoid seeing them. – IGP Apr 11 '23 at 20:21
  • Added code to the OP, I do is read a json file and then create a new file with cloud translate results (PHP code) – gabogabans Apr 11 '23 at 21:57

0 Answers0