-
Notifications
You must be signed in to change notification settings - Fork 0
/
GoogleAPItranslation.php
47 lines (41 loc) · 1.78 KB
/
GoogleAPItranslation.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
// Function to translate text using Google Translate API
function translateText($text, $targetLanguage) {
$apiKey = 'AIzaSyCvYhmuQVyP-O-9tflpHafAVYrehO29oAc';
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=' . $targetLanguage;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
return $responseDecoded['data']['translations'][0]['translatedText'];
}
// Check if the language toggle is triggered
if(isset($_GET['lang']) && $_GET['lang'] == 'ms') {
// Translate the content
$translatedText = translateText($_GET['content'], 'ms');
echo $translatedText;
} else {
// Display original content
echo $_GET['content'];
}
?>
<!-- <button onclick="translateToMalay()">Translate to Malay</button>
<script>
function translateToMalay() {
// Get the current page content
var content = document.body.innerHTML;
// Send a request to translate.php with the content and language parameter
var xhr = new XMLHttpRequest();
xhr.open('GET', 'GoogleAPITranslation.php?content=' + encodeURIComponent(content) + '&lang=ms', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Replace the current page content with the translated content
document.open();
document.write(xhr.responseText);
document.close();
}
};
xhr.send();
}
</script> -->