Skip to content

Instantly share code, notes, and snippets.

@caugner
Created April 25, 2019 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caugner/337931f83752d128579c24f5a083eff1 to your computer and use it in GitHub Desktop.
Save caugner/337931f83752d128579c24f5a083eff1 to your computer and use it in GitHub Desktop.
deepl-translate-multiple-texts
<?php
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\GuzzleException;
require_once 'vendor/autoload.php';
$input = ["Hallo", "Welt"];
print_r($input);
try {
$httpClient = new HttpClient([ 'base_uri' => 'https://api.deepl.com/v2/']);
$response = $httpClient->request('POST', 'translate', [
'form_params' => [
'text' => $input,
'source_lang' => "DE",
'target_lang' => "EN",
'split_sentences' => 0,
'preserve_formatting' => 0,
'auth_key' => "***"
],
]);
$json = $response->getBody()->getContents();
$result = json_decode($json, true);
$output = array_column($result['translations'], 'text');
print_r($output);
} catch (GuzzleException $e) {
echo $e->getMessage();
}
@caugner
Copy link
Author

caugner commented Apr 25, 2019

Expected

Array
(
    [0] => Hallo
    [1] => Welt
)
Array
(
    [0] => Hello
    [1] => world
)

Actual

Array
(
    [0] => Hallo
    [1] => Welt
)
Client error: `POST https://api.deepl.com/v2/translate` resulted in a `400 Bad Request` response:
{"message":"Parameter 'text' not specified."}

@valjes
Copy link

valjes commented Feb 6, 2020

@yemanjo
Copy link

yemanjo commented Jan 1, 2022

Its probably too late but if someone needs solution - json_encode should be used on array:
Example:

  'form_params' => [
            'auth_key' => '***',
            'text' =>  json_encode($input),
            'source_lang' => "EN",
            'target_lang' => "DE",
            'split_sentences' => 0,
            'preserve_formatting' => 0,
        ],

and to get results in format you wanted:

  $json = $response->getBody()->getContents();
  $result = json_decode($json, true);
  $output = array_column($result['translations'], 'text');
  $expectedOutput = json_decode($output[0]);

@renepardon
Copy link

@yemanjo thank you very much - with json it works :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment