文件获取内容-显示file_get_contents对特殊字符失败- PHP


file get contents - Displaying file_get_contents fails on special characters - PHP

我正在尝试使用file_get_contents打开文件。该文件包含"和其他特殊字符。当我尝试用echo $file_contentsPHP中输出该文件的内容时,操作失败,Unexpected token错误。

  1. 如何对这些特殊字符进行编码?
下面是得到错误的代码:
<?php
//the function below displays data from bbMainPage javascript.
function getDataFromLibrary() {
    $tgt_url = $_GET["tgt_url"];
    $file_contents = file_get_contents($tgt_url);
    //echo $tgt_url;
    //echo $file_contents;
    var_dump($file_contents);
    //return $tgt_url;
}
?>

javascript代码:

<html>
<head>
<style>
.hlight{background-color:#ffcc00;}
textarea {
    width:100%;
    height:100%;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
//mention all global variables here.
console.log("this is the start of javascript");
//get all data from the previous script.
var fileContents = "<?php getDataFromLibrary(); ?>";
var tgtURL = <?php echo json_encode($tgt_url); ?>;
console.log("URl obtained = " + tgtURL);
console.log("Text obtained = " + fileContents);   //this is where it fails.
</script>
</head>
</html>

如果使用特殊字符(如空格)打开URI,则需要使用urlencode()对URI进行编码。

PHP在读取utf-8编码文件并将其发送到浏览器时似乎没有任何问题。我只是简单地查了一下。你确定你发送正确的字符集类型的头到浏览器

header('Content-Type: text/html; charset=UTF-8');

您需要目标URL的数据。目标URL应该有特殊字符。所以首先编码你的目标URL,然后你可以得到那个文件的内容。

如果你的文件有问题,那么你应该在处理它之前重新检查文件。