Trying to make an API request to deepL

[ad_1]

I’m an absolute noob in webdev and wanted to build a simple website for fun (learning by doing). The idea is to upload pdf documents in one language and get them translated into another. For this I wanna use the deepL API.
Now, I can’t really get it to work. When I press on “submit” in my html form, i get redirected to a blank page and nothing happens. The script which is supposed to connect to the API just doesn’t seem to get reached or something.
My logic was: using the action attribute with a .php-file which handles the form submission and feeds the pdf-document as a parameter to a php function (which is located in functions.php).

Does anyone have an idea where the issue might be or maybe someone could recommend a whole other way how to execute such API requests?

Here are my code snippets:

**HTML form to upload documents:**

<form action=”translate.php” method=”post” enctype=”multipart/form-data”>
<input type=”hidden” name=”action” value=”translate_document”>
<input type=”file” name=”document_file”>
<select name=”target_lang”>
<option value=”DE”>German</option>
</select>
<input type=”submit” value=”Translate”>
</form>

**Handling the submission ( file “translate.php” located in the public folder):**

<?php
function handle_document_translation() {
if (isset($_FILES[‘document_file’][‘tmp_name’])) {
$file_path = $_FILES[‘document_file’][‘tmp_name’];
$target_lang = $_POST[‘target_lang’];
$auth_key = ‘HERE IS MY KEY;

$translation_result = translate_document($file_path, $target_lang, $auth_key);

if ($translation_result !== false) {
// Translation successful, output the result
echo “Translation Result: ” . $translation_result;
} else {
// Translation failed, output an error message
echo “Translation Failed”;
}
}
}
?>

**The actual script to connect to the API (located in functions.php):**

function translate_document($file_path, $target_lang, $auth_key) {
$api_url = ‘https://api-free.deepl.com/v2/document’;

$request_body = array(
‘target_lang’ => $target_lang,
‘file’ => ‘@’ . $file_path
);

$args = array(
‘body’ => $request_body,
‘headers’ => array(
‘Authorization’ => ‘DeepL-Auth-Key ‘ . $auth_key
)
);

$response = wp_remote_post($api_url, $args);

if (is_wp_error($response)) {
return false;
} else {
$response_body = wp_remote_retrieve_body($response);
return $response_body;
}
}

&#x200B;

[ad_2]
1 Comment
  1. >$response = wp_remote_post($api_url, $args);

    What are the contents of `$response`?

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer