I'm trying to use PHP to generate a JavaScript switch block by taking input from TemplateList.txt. It works fine when I only have one line in TemplateList.txt, but when I have two or more I get an error in the console saying I have a
SyntaxError: unterminated string literal
on the line of the php opening tag, I can't see any unclosed strings.
<?php
$listHandle = fopen('templates/TemplateList.txt', 'r');
while (!feof($listHandle)) {
$thisTemplate = fgets($listHandle);
echo "case \"" . $thisTemplate . "\": " . $thisTemplate . "(); break; ";
}
fclose($listHandle);
?>
My TemplateList.txt file looks like this:
heart_by_john
dog_by_sue
What am I doing wrong?
The fgets()
function includes the line break in the returned string, so you add a line break to your JS inside the string. Replace
$thisTemplate = fgets($listHandle);
by
$thisTemplate = trim(fgets($listHandle));
Hi that's because there is a line break after each word in your list
This code works for me.
$path = 'templates/TemplateList.txt';
$str = '';
if(file_exists($path)){
$listHandle = file($path, FILE_IGNORE_NEW_LINES);
foreach ($listHandle as $line_num => $line){
$str .= "case \"" . $line . "\": " . $line . "(); break; ";
}
}
echo $str;