Js + PHP:从文本文件中读取值

时间:2014-10-31 08:17:37

标签: javascript php parsing

我正在尝试从php上的服务器上的文本文件中读取值,并在js中使用它们。我正在使用代码(在stackoverflow中找到),它似乎针对我需要的东西,但是得到一个错误(Uncaught SyntaxError:Unexpected token<),它似乎与php行相关。

LM.txt一行:ID,LAT,LNG

 <script >   (function(){
     <?php echo "var fileContent = '" . file_get_contents("graphdata/LM.txt"). "'," ; ?>
     alerts = fileContent.split("\n").map(function(lineItem){
        // Assuming each line is csv: ID,LAT,LNG 
        // and that there are no commas in the values
        var field = lineItem.split(",");
        return {ID: field[0], LAT: field[1], LNG: fields[2]};
     });
     // now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}];   })(); </script>

我能做什么?

3 个答案:

答案 0 :(得分:0)

你的脚本文件是否有.PHP扩展名? (否则它将不会被PHP-Interpreter处理)

答案 1 :(得分:0)

这个怎么样,似乎你的代码在内联评论中包含了一些标记 - &gt; //现在提醒......

<script >   
(function() {
    var fileContent = '<?php echo addslashes(file_get_contents("graphdata/LM.txt")) ?>',
    alerts = fileContent.split("\n").map( function(lineItem){
                  // Assuming each line is csv: ID,LAT,LNG    
                  // and that there are no commas in the values
                var field = lineItem.split(",");
                return { ID: field[0], LAT: field[1], LNG: fields[2] };
    });
   // now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}]; 
})();
</script>

答案 2 :(得分:0)

<?PHP
    $filecontent = str_replace("\n",'\n',file_get_contents("graphdata/LM.txt"));
    echo '
        <script type="text/javascript">
            var fileContent = "'.$filecontent.'";
            // now the JS variable fileContent has the content of your file
            var alerts = fileContent.split("\n").map(function(lineItem){
                 var field = lineItem.split(",");
                 return {ID: field[0], LAT: field[1], LNG: field[2]};
            });
        </script>
    ';
?>
相关问题