为什么 file_get_contents 不能处理 html 文件?
why is file_get_contents not working with html files?
我有一个 editor.php 页面,它从不同的页面获取文件名并将其加载到代码镜像编辑器中。我的问题是它只适用于 .txt 文件,但不适用于 .html 或 .java 文件。
<?php
$login=$_COOKIE['login'];
$directory = "userFiles/" . $login . "/";
$filename = isset($_POST['files']) ? $_POST['files'] : false;
$content = @file_get_contents($directory.$filename);
?>
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script src='codemirror/lib/codemirror.js'></script>
<script src='codemirror/mode/css/css.js'></script>
<script src='codemirror/mode/htmlmixed/htmlmixed.js'></script>
<link rel='stylesheet' href='codemirror/lib/codemirror.css'>
<style>
.CodeMirror {
width: 100%;
height: 85%;
}
</style>
</head>
<body>
<textarea id="code" name="code" autofocus></textarea>
<button class="button" id="save">Save</button>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: 'text/html',
tabMode: 'indent',
lineNumbers: true,
lineWrapping: true,
autoCloseTags: true
});
editor.setValue("<?php echo $content;?>"+);
</script>
</body>
</html>
最可能的解释是此类文件有很多双引号 ("
)。现在
会发生什么
"<?php echo $content;?>"
确实:您会得到像 "<a href="google.com">link</a>"
这样的字符串。 JavaScript 试图解释这些,但无法理解你突然停止字符串,毕竟 JavaScript 看到:
"<a href="google.com">link</a>"
^ ^ ^
| | \-- something weird??!
| \--end string
\--start string
我建议您查看生成页面的原始源代码来检查这一点。
解决方案?
您可以按照@Amadan 的建议解决此问题,方法是使用例如 JSON 之类的载体。通过json_encode
,您将字符串编码为一种格式,JavaScript 可以理解。您也可以使用不同的格式(在其中转义引号),但在这种情况下,JavaScript 将需要进行一些未设计的解码(因此您需要编写解码算法)。
我有一个 editor.php 页面,它从不同的页面获取文件名并将其加载到代码镜像编辑器中。我的问题是它只适用于 .txt 文件,但不适用于 .html 或 .java 文件。
<?php
$login=$_COOKIE['login'];
$directory = "userFiles/" . $login . "/";
$filename = isset($_POST['files']) ? $_POST['files'] : false;
$content = @file_get_contents($directory.$filename);
?>
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script src='codemirror/lib/codemirror.js'></script>
<script src='codemirror/mode/css/css.js'></script>
<script src='codemirror/mode/htmlmixed/htmlmixed.js'></script>
<link rel='stylesheet' href='codemirror/lib/codemirror.css'>
<style>
.CodeMirror {
width: 100%;
height: 85%;
}
</style>
</head>
<body>
<textarea id="code" name="code" autofocus></textarea>
<button class="button" id="save">Save</button>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: 'text/html',
tabMode: 'indent',
lineNumbers: true,
lineWrapping: true,
autoCloseTags: true
});
editor.setValue("<?php echo $content;?>"+);
</script>
</body>
</html>
最可能的解释是此类文件有很多双引号 ("
)。现在
"<?php echo $content;?>"
确实:您会得到像 "<a href="google.com">link</a>"
这样的字符串。 JavaScript 试图解释这些,但无法理解你突然停止字符串,毕竟 JavaScript 看到:
"<a href="google.com">link</a>"
^ ^ ^
| | \-- something weird??!
| \--end string
\--start string
我建议您查看生成页面的原始源代码来检查这一点。
解决方案?
您可以按照@Amadan 的建议解决此问题,方法是使用例如 JSON 之类的载体。通过json_encode
,您将字符串编码为一种格式,JavaScript 可以理解。您也可以使用不同的格式(在其中转义引号),但在这种情况下,JavaScript 将需要进行一些未设计的解码(因此您需要编写解码算法)。