diff --git a/src/Translator.php b/src/Translator.php index 2426b25..6a5d708 100644 --- a/src/Translator.php +++ b/src/Translator.php @@ -171,6 +171,12 @@ public function translateText($texts, ?string $sourceLang, string $targetLang, a $this->checkStatusCode($response); list(, $content) = $response; + + // Deepl API responses might have invalid UTF8 sequence + // @see https://github.com/DeepLcom/deepl-php/pull/43 + mb_substitute_character(0xFFFD); + $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8'); + try { $decoded = json_decode($content, true, 512, \JSON_THROW_ON_ERROR); } catch (JsonException $exception) { diff --git a/tests/TranslateTextTest.php b/tests/TranslateTextTest.php index de5658e..d7e2c40 100644 --- a/tests/TranslateTextTest.php +++ b/tests/TranslateTextTest.php @@ -37,6 +37,21 @@ public function testMultipleText(?ClientInterface $httpClient) $this->assertEquals('en', $result[1]->detectedSourceLang); } + /** + * @dataProvider provideHttpClient + */ + public function testHandlingResponseWithInvalidUtf8(?ClientInterface $httpClient) + { + $this->needsRealServer(); + $translator = $this->makeTranslator([TranslatorOptions::HTTP_CLIENT => $httpClient]); + $input = 'Portal'; + $result = $translator->translateText($input, 'en', 'fr', [ + TranslateTextOptions::TAG_HANDLING => 'xml', + TranslateTextOptions::IGNORE_TAGS => 'notranslate', + ]); + $this->assertInstanceOf(TextResult::class, $result); + } + /** * @dataProvider provideHttpClient */