注意:未定义的偏移量:第17行的C:\ xampp \ htdocs \ weather-scrapper \ forecast.php中的1 [关闭]

问题描述 投票:-1回答:1

使用下面的代码,我有一个问题,我不知道如何解决。我正试图从天气网站上爆炸字符串

<?php
$scrapedString       = '3 day weather forecast summary:</br><span class="read-more-small"><span class="read-more-content"> <span class="phrase">';
$secondScrapedString = '</span></span></span>';

$file_headers[] = "";

if ($_GET['city']) {

    $city         = str_replace(' ', '', $_GET['city']);
    $forecastPage = file_get_contents("https://www.weather-forecast.com/locations/" . $city . "/forecasts/latest");
    if ($file_headers[0] == 'HTTP/1.1 404 not found') {
        $exists = false;
    } else {

        $pageArray = explode($scrapedString, $forecastPage);

        $secondPageArray = explode($secondScrapedString, $pageArray[1]);

        $weatherResult = $secondPageArray[0];   
    } 
}
?>
php html weather
1个回答
1
投票

看起来像$pageArray[1]没有设置。

只需将其包装在if中,如果它未设置,则不会发生此错误。

$secondScrapedString = ''; 
$file_headers[] = ""; 
if($_GET['city']){ 
  $city = str_replace(' ', '', $_GET['city']); 
  $forecastPage = file_get_contents("https://www.weatherforecast.com/locations/".$city."/forecasts/latest");
  if($file_headers[0] == 'HTTP/1.1 404 not found'){ 
    $exists = false; 
  } else {
     $pageArray = explode( $scrapedString, $forecastPage)
     if(isset($pageArray[1])){
       $secondPageArray = explode($secondScrapedString, $pageArray[1]); 
       if(isset($secondPageArray[0])){
         $weatherResult = $secondPageArray[0]; 
       }
     }
  } 
} 
?>

这样做看起来会消除你的错误,但这里似乎不仅仅是一个未定义的索引。

  • $file_headers在哪里填充,可能应该检查数据是否返回$forecastPage
  • $exists似乎没有做任何事情
  • 爆炸2级深度似乎有点奇怪,preg_split怎么样
  • $scrapedString没有定义

但仅仅这一点并不是我所不能确定的所有代码。

无论哪种方式,希望这有帮助,

© www.soinside.com 2019 - 2024. All rights reserved.