PHP嵌入JavaScript出现SyntaxError: unterminated string literal错误原因排查
SyntaxError: unterminated string literal in Your Code Hey there, let's break down exactly why you're hitting this error and how to fix it quickly.
The Root Cause
Your current code injects the raw content of testtext directly into a JavaScript string without any escaping. Here are the most common issues that trigger the unterminated string literal error:
- Line breaks in the file: If
testtexthas any newlines, PHP will output them directly into the JS string. JavaScript doesn't allow unescaped line breaks inside quoted strings, so the interpreter sees the line break as the end of the string and chokes on the remaining content. - Double quotes in the file: If
testtextcontains a"character, it will close the JS string prematurely. For example, if your file hasHello "World", the output becomesconsole.log(" Hello "World" ");— JS reads the second"as the end of the string, leaving the rest of the text unclosed. - Other unescaped special characters: Things like backslashes (
\) or tabs can also disrupt the JS string syntax.
The Simple Fix
Instead of echoing raw content, use PHP's json_encode() function. It automatically escapes all characters that would break JavaScript strings, including newlines, quotes, and special symbols. Here's how to modify your code:
<script> console.log(<?php $geladen = file_get_contents("./testtext"); echo json_encode($geladen); ?>); </script>
A few notes on this fix:
json_encode()adds the surrounding double quotes for you, so you don't need to include them in the JS code anymore.- This works for any content in
testtext— whether it's plain text, multi-line content, or text with special characters.
Why This Works
json_encode() converts the PHP string into a valid JSON string, which is 100% compatible with JavaScript string syntax. It handles all the escaping heavy lifting, so you don't have to manually replace newlines with \n or quotes with \" (which is error-prone anyway).
内容的提问来源于stack exchange,提问作者Kai Burgdorf

