首页 > 解决方案 > file_get_contents PHP Uncaught SyntaxError:无效或意外令牌

问题描述

当我尝试让我们 file_get_contents 了解我的天气时,它向我显示了这个错误

我做错了什么 ??

我不能这样做:

<?php
function getWeather_PHP($location) {
  $l_location = (string)$location;
  $url = "http://api.openweathermap.org/data/2.5/weather?".$l_location."&lang=en&units=metric&appid=MY_API_KEY";
  $url = (string)$url;
  $contents = file_get_contents($url); //error occur here
  ...
  return weather_data;
?>

在同一个 php 文件中的脚本中

<script>

    var inputString  = "PLACE_LOCATION"

    var php_result = "<?php
                       $php_inputString = '"+inputString+"';
                       echo getWeather_PHP($php_inputString);
                      ?>";
</script>

错误是: 在此处输入图像描述

我得到的另一个错误报告是 警告:file_get_contents("+this_url+"): failed to open stream: No such file or directory in /opt/lampp/htdocs/Index.php on line 50

标签: javascriptphp

解决方案


var php_result = "<?php
                   $php_inputString = '"+inputString+"';
                   echo getWeather_PHP($php_inputString);
                  ?>";

PHP 在服务器上进行评估,早在 Javascript 运行之前。PHP 解释器<?php … ?>直接输出标签之外的所有内容,而不以任何方式对其进行解释。

从 PHP 的角度来看,$php_inputstring是设置为文字文本"+inputString+"。这导致getWeather_PHP()尝试获取 city 的天气"+inputString+",但失败了。

如果您需要getWeather_PHP()可从 Javascript 调用该函数,则需要将其公开为单独的 AJAX 端点。无法以您在此处尝试的方式使 Javascript 和 PHP 互通。


推荐阅读