You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP嵌入JavaScript出现SyntaxError: unterminated string literal错误原因排查

Fixing the 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 testtext has 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 testtext contains a " character, it will close the JS string prematurely. For example, if your file has Hello "World", the output becomes console.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:53:07