Skip to content

Instantly share code, notes, and snippets.

@hctilg
Created July 24, 2025 06:57
Show Gist options
  • Save hctilg/a816afc9925bb07b5e1bb85c7fa555ad to your computer and use it in GitHub Desktop.
Save hctilg/a816afc9925bb07b5e1bb85c7fa555ad to your computer and use it in GitHub Desktop.
Subtitle (srt files) translation with PHP
<?php
function translate($text, $source_lang = 'en', $target_lang = 'fa') {
$url = 'https://translate.googleapis.com/translate_a/single?';
$url .= http_build_query([
'client' => 'gtx',
'sl' => $source_lang,
'tl' => $target_lang,
'dt' => 't',
'q' => $text,
]);
$response = file_get_contents($url);
$result = json_decode($response, true);
return $result[0][0][0] ?? false;
}
$srt_filename = "Share.2023.1080p.AMZN.WEB-DL.DDP5.1.H.264.srt";
echo "[*] Loading srt file..." . PHP_EOL;
$srt_file = file_get_contents($srt_filename);
file_put_contents("translated.$srt_filename", '');
$parts = explode("\n\n", $srt_file);
$length = count($parts);
foreach ($parts as $index => $part) {
$lines = explode("\n", $part);
$details = implode("\n", array_slice($lines, 0, 2));
$paragraph = implode("\n", array_slice($lines, 2));
$translated_paragraph = translate($paragraph);
file_put_contents(
"translated.$srt_filename",
($index == 0 ? '' : "\n") . "$details\n$translated_paragraph" . ((($length - $index) == 1) ? '' : "\n"),
FILE_APPEND
);
$precent = (int)(($index * 100) / $length);
echo "\r[$precent% $index/$length] Translating sentences...";
}
echo "\r[#] Translation completed." . str_repeat(' ', ((strlen("$length") * 2) + 10)) . PHP_EOL;
echo " └─╼ ‘translated." . $srt_filename . "’ saved." . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment