-1

when I try to get us file_get_contents to my weather, it shows me this error

What did I do wrong ??

Cant I just do:

<?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;
?>

And in a script in same php file

<script>

    var inputString  = "PLACE_LOCATION"

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

And the Error is : enter image description here

another error report I got is Warning: file_get_contents("+this_url+"): failed to open stream: No such file or directory in /opt/lampp/htdocs/Index.php on line 50

M.H
  • 21
  • 4
  • 1
    Probably need an `echo` before the `getWeather_PHP`. The `return` sends the value back but you don't do anything with it in the PHP. – user3783243 Sep 30 '18 at 22:46
  • You are also missing a `$` in your `return $weather_data;`. Regarding the error in the browser console, I'm pretty sure you are missing some js files. – msg Sep 30 '18 at 22:52
  • Oh forgot the type the echo here I do have that in my code – M.H Sep 30 '18 at 23:23
  • another report I got is Warning: file_get_contents("+this_url+"): failed to open stream: No such file or directory in /opt/lampp/htdocs/Index.php on line 50
    – M.H Sep 30 '18 at 23:24
  • Oh cool, so you found the error. Your url is incorrect. Maybe you should remove `$url = (string)$url;`. – Ibu Sep 30 '18 at 23:31
  • @lbu You're going down a blind alley. The `(string)` casts are unnecessary, but aren't the cause of the problem. –  Sep 30 '18 at 23:39

1 Answers1

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

PHP is evaluated on the server, long before Javascript runs. The PHP interpreter outputs all content outside <?php … ?> tags directly, without interpreting it in any way.

From the perspective of PHP, $php_inputstring is set to the literal text "+inputString+". This leads getWeather_PHP() to attempt to get the weather in the city "+inputString+", which fails.

If you need the getWeather_PHP() function to be callable from Javascript, you will need to expose it as a separate AJAX endpoint. There is no way to interwork Javascript and PHP in the way you're attempting here.

  • thank you so so much for helping but just wondering if I can just ajax_post a JS variable ? and get it in PHP? – M.H Sep 30 '18 at 23:45