2017-09-10 69 views
-3

从我开始学习PHP到现在已经有几个月了,而且我遇到了几十个问题,幸运的是我能够解决它们,但今天的问题,不是重复的问题,可能是不同的,我已经阅读了关于这个问题的所有堆栈溢出问题,但他们没有任何帮助。

我收到以下错误:

Notice: Undefined index: city in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 99

这是我的代码:

<?php 

    $weather = ""; 
    $error = ""; 

    if ($_GET['city']) { 

    $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".urlencode($_GET['city']).",uk&appid=Hidden"); 

     $weatherArray = json_decode($urlContents, true); 

     if ($weatherArray['cod'] == 200) { 

      $weather = "The weather in ".$_GET['city']." is currently '".$weatherArray['weather'][0]['description']."'. "; 

      $tempInCelcius = intval($weatherArray['main']['temp'] - 273); 

      $weather .= " The temperature is ".$tempInCelcius."&deg;C and the wind speed is ".$weatherArray['wind']['speed']."m/s."; 

     } else { 

      $error = "Could not find city - please try again."; 

     } 

    } 
?> 

我也使用XAMPP和php.ini的是有太多。

+0

显示导致此错误的网址 – wrager

+0

@wrager:http://api.openweathermap.org/data/2.5/weather?q =“.urlencode($ _ GET ['city'])。”,uk&appid =隐藏** –

+0

@CaplinYT ...是的,这个问题确切地概述了这个通知的含义。您在$ _GET中没有“城市”索引。 – Devon

回答

2

从你的代码语法,我认为你是问题是你如何得到city。你的错误表明它找不到$_GET中的city的索引;所以基本上还没有确定。运行代码前加一个isset检查,这将避免任何错误:

if (isset($_GET['city'])) { 
    $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".urlencode($_GET['city']).",uk&appid=Hidden"); 
    //... 
} 

这将阻止该代码运行,并避免任何错误;现在检查你的网址,确保它包含:https://example.com?city=somecity。这应该可以解决这个错误。