Created
September 19, 2018 11:29
-
-
Save natanfelles/6ebb44138c667be7289f57016e8b2c0a to your computer and use it in GitHub Desktop.
YouTube Subtitles - XML to SRT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$argv = [ | |
'', | |
'filename.xml' | |
]; | |
if(empty($argv[1])) { | |
exit('Argument one must contain the TimedText file.'); | |
} | |
if(empty($argv[2])) { | |
$argv[2] = str_replace('.xml', '.srt', $argv[1]); | |
} | |
$ttfile = __DIR__ . '/'. $argv[1]; | |
$srtfile = __DIR__ . '/'. $argv[2]; | |
$dom = new DOMDocument; | |
// Prevent DOMDocument::loadHTML error | |
libxml_use_internal_errors(true); | |
$dom->loadXML(file_get_contents($ttfile)); | |
function srt_timestamp($seconds, $is_miliseconds = false) { | |
if($is_miliseconds) { | |
$milliseconds = $seconds * 1000; | |
} else { | |
$milliseconds = $seconds; | |
} | |
$seconds = floor($milliseconds / 1000); | |
$minutes = floor($seconds / 60); | |
$hours = floor($minutes / 60); | |
$milliseconds = $milliseconds % 1000; | |
$seconds = $seconds % 60; | |
$minutes = $minutes % 60; | |
return ($hours < 10 ? '0' : '') . $hours . ':' | |
. ($minutes < 10 ? '0' : '') . $minutes . ':' | |
. ($seconds < 10 ? '0' : '') . $seconds . ',' | |
. ($milliseconds < 100 ? '0' : '') . ($milliseconds < 10 ? '0' : '') . $milliseconds; | |
} | |
$constents = ''; | |
foreach ($dom->getElementsByTagName('p') as $k => $sub) { | |
$constents .= srt_timestamp($sub->getAttribute('t')) . ' --> '; | |
$constents .= srt_timestamp($sub->getAttribute('t') + $sub->getAttribute('d')) . PHP_EOL; | |
$constents .= $sub->nodeValue . PHP_EOL; | |
$constents .= PHP_EOL; | |
} | |
foreach ($dom->getElementsByTagName('text') as $k => $sub) { | |
$constents .= srt_timestamp($sub->getAttribute('start'),true) . ' --> '; | |
$constents .= srt_timestamp($sub->getAttribute('start') + $sub->getAttribute('dur'),true) . PHP_EOL; | |
$constents .= trim(html_entity_decode($sub->nodeValue)) . PHP_EOL; | |
$constents .= PHP_EOL; | |
} | |
file_put_contents($srtfile, $constents); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment