diff --git a/classes/template/TemplateHandler.class.php b/classes/template/TemplateHandler.class.php
index 123fcdc6b..97030c8fb 100644
--- a/classes/template/TemplateHandler.class.php
+++ b/classes/template/TemplateHandler.class.php
@@ -286,6 +286,9 @@ class TemplateHandler
// detect existence of autoescape config
$this->config->autoescape = (strpos($buff, ' autoescape="') === false) ? null : false;
+ // remove UTF-8 BOM and convert CRLF to LF
+ $buff = preg_replace(['/^\xEF\xBB\xBF/', '/\r\n/'], ['', "\n"], $buff);
+
// replace comments
$buff = preg_replace('@@s', '', $buff);
diff --git a/tests/unit/classes/TemplateHandlerTest.php b/tests/unit/classes/TemplateHandlerTest.php
index aeaa5a1c0..399ca5518 100644
--- a/tests/unit/classes/TemplateHandlerTest.php
+++ b/tests/unit/classes/TemplateHandlerTest.php
@@ -263,7 +263,7 @@ class TemplateHandlerTest extends \Codeception\TestCase\Test
'?> foo->bar ?? false){ ?>
'
),
array(
- '' . "\n" . '
',
+ '' . "\r\n" . '
',
'?>' . "\n" . ' foo->bar ?? false){ ?>
'
),
array(