PHP致命错误:在非对象上调用成员函数setTimezone()

时间:2017-10-27 10:29:57

标签: php

我在错误日志中运行php时出现以下错误:

  

PHP致命错误:在a上调用成员函数setTimezone()   非对象   /var/www/vhosts/*********.gr/httpdocs/protected/TemplateGenerator.php   在第525行

这是php:

   //     $val1 = "28/02/2015 18:00";
        $date1 = DateTime::createFromFormat('d/m/y H:i', $val1, new DateTimeZone('Europe/Athens'));
        $date1->setTimezone(new DateTimeZone('Europe/Athens'));
  //      $current_month = $date1->format('m');
   //     $datetime1 = new DateTime($date);
        $now = new DateTime();
        $now->setTimezone(new DateTimeZone('Europe/Athens'));
        $days = (int) $now->diff($date1)->days;
        $hours = (int) $now->diff($date1)->format("%H");
        // $date1->format(DateTime::ISO8601)

我找不到任何与php相关的错误。 有什么帮助吗?

编辑:$ val1 = $ date。" " 。 $时间;

完整代码:

<?php
    require_once "forecast_api/ForecastIconsGenerator.php";

/**
 * Class TemplateGenerator
 * this is a class that runs from a cron job and generates a stations forecast template.
 * To use, you create an instance and invoke the createTemplate method.
 * If there is a need to add a new station, or make modifications to some data provided please modify
 * stations.csv file that exists in the same folder.
 */
    class TemplateGenerator {
        /**
         * @var array
         * Contains the hardcoded headers of downld02.txt file.
         * Created for future use
         */
        private $download_headers = [
            "Date", "Time", "Temp Out", "Hi Temp", "Low Temp", "Out Hum", "Dew Pt.",
            "Wind Speed", "Wind Dir", "Wind Run" , "Hi Speed", "Hi Dir", "Wind Chill", "Heat Index",
            "THW Index", "Bar", "Rain", "Rain Rate", "Heat D-D", "Cool D-D", "In Temp", "In Hum",
            "In Dew", "In Heat", "In EMC", "In Air Density", "Wind Samp", "Wind Tx", "ISS Recept", "Arc Int"
        ];

        private $orders = ['Χανίων' => 1, 'Ρεθύμνου' => 2, 'Ηρακλείου' => 3, 'Λασιθίου' => 4];

        /**
         * @var array
         * Contains an array of associative arrays, each one representing a region that
         * needs to be included in the template. Each associative array has values with about same key names as the
         * headers of stations.csv .
         */
        private $stations;

        /**
         * Creates a new forecast generator instance.
         * Instantiates the regions field with the values extracted from stations.csv .
         */
        function __construct() {
            $this->stations = array();
            $handle = fopen("/var/www/vhosts/meteokrites.gr/httpdocs/protected/stations.csv", 'r');
            $headers = fgetcsv($handle, 1000, ",");

            $h = [];
            $c = [];
            $r = [];
            $l = [];            


            while (($row = fgetcsv($handle, 1000, ","))) {

                $order = 0;

                switch (trim($row[2])) {
                    case 'Χανίων':
                        array_push($c, array("fakelos" => $row[0], "perioxh" => $row[1], "nomos" => $row[2], "foreas" => $row[3], "url" => $row[4], "link" => $row[5],"altitude" => $row[6],"parse_type" => $row[7], "order" => $order));
                        break;
                    case 'Ρεθύμνου':
                        array_push($r, array("fakelos" => $row[0], "perioxh" => $row[1], "nomos" => $row[2], "foreas" => $row[3], "url" => $row[4], "link" => $row[5],"altitude" => $row[6],"parse_type" => $row[7], "order" => $order));
                        break;
                    case 'Ηρακλείου':
                        array_push($h, array("fakelos" => $row[0], "perioxh" => $row[1], "nomos" => $row[2], "foreas" => $row[3], "url" => $row[4], "link" => $row[5],"altitude" => $row[6],"parse_type" => $row[7], "order" => $order));
                        break;
                    case 'Λασιθίου':
                        array_push($l, array("fakelos" => $row[0], "perioxh" => $row[1], "nomos" => $row[2], "foreas" => $row[3], "url" => $row[4], "link" => $row[5],"altitude" => $row[6],"parse_type" => $row[7], "order" => $order));
                        break;                                                                    
                    default:
                        break;
                }

                //array_push($this->stations, array("fakelos" => $row[0], "perioxh" => $row[1], "nomos" => trim($row[2]), "foreas" => $row[3], "url" => $row[4], "link" => $row[5],"altitude" => $row[6],"parse_type" => $row[7], "order" => $order));
            }

            $this->stations = array_merge($c, $r, $h, $l);

            fclose($handle);
        }

        private function getDegrees($rotation, $direction) {
            foreach ($rotation as $temp) {
                if ($temp[0] === $direction) {
                    return $temp[1];
                }
            }
        }

        private function getWindDirectionIcon($wind_dir) {
            $rotations = [['N', 0], ['S', 180], ['E', 90], ['W', 270], ['NE', 45], ['NW', 315], ['SE', 135], ['SW', 225], ['NNE', 22.5], ['ENE', 67.5], ['ESE', 112.5], ['SSE', 157.5],
                ['SSW', 202.5], ['WSW', 247.5], ['WNW', 292.5], ['NNW', 337.5]];
            $degree = $this->getDegrees($rotations, $wind_dir);
            return $degree;
        }

        /**
         * @param $folder the folder name of the current staion
         * @return array the forecast data extracted from the most recent entry of downld02.txt
         */
        function parseDownloadFile($folder,$url,$type) {

            $file = $url.$folder."/ZWNTANA.htm";

            if(preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $file) ){//full url http://...
                $headers = get_headers($file);
                $file_exist = stripos($headers[0],"200 OK")?true:false;

                if(!$file_exist){
                    return false;
                }            

            }
            else{
                if (!file_exists($file)) {//directory ../hrakleio/....
                    return false;
                }        
            }  

            if($type == 1){
                $file = $url.$folder."/ZWNTANA.htm";

                $handle = fopen($file, "r");

                $forecast_data = array();                
                if ($handle) {
                    while(! feof($handle))
                      {
                      preg_match_all('/"([^"]*(?:\\"[^"]*)*)"/', fgets($handle), $matches); 
                      $forecast_data[] = trim($matches[1][0]);
                      }
                    fclose($handle);

                    return $forecast_data;
                }
                else {
                    return false;
                }
            }
            else if($type == 2){
                $file = $url.$folder."/ZWNTANA.htm";

                $handle = fopen($file, "r");

                $forecast_data = array();                
                $homepage = file_get_contents($file);
                if ($handle) {

                        preg_match_all('/"([^"]*(?:\\"[^"]*)*)"/', $homepage, $matches); 
                        $bb = explode(';', $matches[1][0]);

                        foreach ($bb as $key => $value) {
                            preg_match('/"([^"]+)"/', $value, $m);

                            if(isset($m[1]) && !empty($m)){
                                $forecast_data[] = $m[1];
                            }
                        }

                        return $forecast_data;
                }
                else {
                    return false;
                }                
            }
            else if($type == 3){
//                 $handle = simplexml_load_file($url);


//                 $xmlparser = xml_parser_create();

//                 $fp = fopen($url, 'r');
//                 $xmldata = fread($fp, 4096);

// xml_parse_into_struct($xmlparser,$xmldata,$values);

// xml_parser_free($xmlparser);
// var_dump($values);
                // foreach ($handle->TelStation as $key => $value) {
                //    if((string)$value->attributes()[0] == $folder){
                //         //$last_time = end($value->time);
                //         if(isset($value->time)){
                //             $int = count($value->time) -1;
                //             var_dump($value->time[1]->attributes());
                //             var_dump($value->time['AirTemperature']->attributes());
                //         }

                //         //->attributes()[0]
                //    }
                // }

               // die();
            }
            else if($type == 4)
            {
                require_once 'simple_html_dom.php';

                $file = $url.$folder."/ZWNTANA.htm";

                $html = file_get_html($file);

                if(!$html)
                    return false;

                $table = $html->find('td');

                $rowData = array();

                foreach($table as $row) 
                {

                    $bb = explode('=', $row->plaintext);

                    $c = str_replace(";","",$bb[1]);
                    $c = str_replace("\"","",$c);
                    $c = preg_replace('/[^(\x20-\x7F)]*/','', $c);

                    $dd = explode(" ", $c);

                    $forecast_data[] = $dd[0];

                } 

                return $forecast_data;             
            }
        }

        /**
         * @param $folder string the folder name of the current station
         * @return array day's forecast data about the rain
         */
        private function parseMonthFile($folder,$url) {
            date_default_timezone_set(TIMEZONE);
            $today = getdate();
            $current_day = $today["mday"];
            $rain_data_day = array();

            $file = $url.$folder."/NOAAMO.TXT";
            $handle = fopen($file, "r");

            if ($handle) {
                // ignore the first 3 lines
                fgets($handle); fgets($handle);fgets($handle);
                // get the elevation
                $line = fgets($handle);
                $data = preg_split('/\s+/', $line);
                $elevation = $data[1];
                $rain_data_day[1] = $elevation;
                $count = 0;

                while (($line = fgets($handle)) !== false) {
                    if ($line[0] === ' ') {
                        $line = substr($line, 1);
                    }
                    $data = preg_split('/\s+/', $line);
                    if ( !($line[0] === '-') && ($count == 1) ) {
                        if ($data[0] == $current_day) {
                            // get the current data of RAIN column
                            $temp_rain =  $this->parseDownloadFile($folder,$url);
                            if(!isset($data[8])){

                                $rain_data_day[0] = $temp_rain[65];
                            }
                            else{
                            $rain_data_day[0] = $data[8];
                            }
                            return $rain_data_day;
                        }
                    }
                    if ( $line[0] === '-' ) {
                        $count++;
                    }
                }
                fclose($handle);
            } else {
                // error opening the file.
            }
        }

        public function convertToBeaufort($speed_km){
            if($speed_km < 1){
                return 0;
            }
            else if(($speed_km >= 1) && ($speed_km <= 5.4)){
                return 1;
            }
            else if(($speed_km >= 5.5) && ($speed_km <= 11.9)){
                return 2;
            }
            else if(($speed_km >= 12) && ($speed_km <= 19.4)){
                return 3;
            }
            else if(($speed_km >= 19.5) && ($speed_km <= 28.4)){
                return 4;
            }
            else if(($speed_km >= 28.5) && ($speed_km <= 38.5)){
                return 5;
            }
            else if(($speed_km >= 38.6) && ($speed_km <= 49.7)){
                return 6;
            } 
            else if(($speed_km >= 49.8) && ($speed_km <= 61.6)){
                return 7;
            }
            else if(($speed_km >= 61.7) && ($speed_km <= 74.5)){
                return 8;
            }
            else if(($speed_km >= 74.6) && ($speed_km <= 87.8)){
                return 9;
            }
            else if(($speed_km >= 87.9) && ($speed_km <= 102.2)){
                return 10;
            }
            else if(($speed_km >= 102.3) && ($speed_km <= 117.4)){
                return 11;
            }
            else if($speed_km >= 117.5){
                return 12;
            }
            else{
                return 0;
            }                                                                                                           
        }

        /**
         * @param $folder the folder name of the current station
         * @return array year's and month's forecast data about the rain
         */
        private function parseYearFile($folder, $date,$url) {
            $file = $url.$folder."/NOAAYR.TXT";
            $handle = fopen($file, "r");
            $date = DateTime::createFromFormat('d/m/Y', $date);
            $current_month = $date->format('m');

            $rain_data = array();

            if ($handle) {
                $line = fgets($handle);
                $count = 0;
                while (($line = fgets($handle)) !== false) {
                    $row = preg_split('/\s+/', $line);
                    if ( !($line[0] === '-') && ($count == 3) ) {
                        if ($row[2] == $current_month) {
                            $rain_data[0] = $row[3];
                        }
                    }
                    elseif (!($line[0] === '-') && ($count == 4)) {
                        $rain_data[1] = $row[1];
                        fclose($handle);
                        return $rain_data;
                    }
                    if ( $line[0] === '-' ) {
                        $count++;
                    }
                }
            } else {
                // error opening the file.
            }
        }

        /**
         * Concats the template of each station to create the html template file that our web page uses.
         */
        public function createTemplate() {

            $html = '
                <html>
                <head>
                    <meta charset="UTF-8">
                    <link href="../assets/css/template.css?v=1.1" type="text/css" rel="stylesheet" >
                </head>
                <body>
                    <table id="template">
                        <tr>
                            <th rowspan="2" style="width: 55px;">Ημ/νία</th>
                            <th rowspan="2" style="width: 40px;">Ώρα</th>
                            <th rowspan="2" style="width: 70px;">Νομός</th>
                            <th rowspan="2" style="width: 110px;">Περιοχή</th>
                            <th rowspan="2" style="width: 72px;padding-top: 20px;">Υψόμετρο<br>(m)</th>
                            <th rowspan="2" style="width: 60px;">Φορέας</th>
                            <th colspan="3" style="width: 129px;height: 25px !important;"> Υετός (mm)</th>
                            <th colspan="6" style="width: 342px;height: 25px !important;">Live καιρικές συνθήκες</th>
                        </tr>
                        <tr>
                            <th valign="bottom"><span style="padding-left:10px;">Ετήσιος</span><p style="margin:10px;">&nbsp;</p></th>
                            <th valign="bottom"><span style="padding-left:10px;">Μηνιαίος</span><p style="margin:12px;">&nbsp;</p></th>
                            <th valign="bottom"><span style="padding-left:10px;">Ημερήσιος</span><p style="margin:14px;">&nbsp;</p></th>
                            <th valign="bottom"><span style="padding-left:10px;">Πίεση</span><p style="margin:6px;">(hPa)</p></th>
                            <th valign="bottom"><span style="padding-left:51px;">Ταχ. Ανέμου</span><p style="margin:6px;">(Bf)</p></th>
                            <th valign="bottom"><span style="padding-left:10px;">Διευθ.Ανέμου</span><p style="margin:19px;">&nbsp;</p></th>
                            <th valign="bottom"><span style="padding-left:27px;">Υγρασία</span><p style="margin:6px;">(%)</p></th>
                            <th valign="bottom"><span style="padding-left:60px;">Θερμοκρασία</span><p style="margin:6px;">(&degC)</p></th>
                            <th valign="bottom"><span style="padding-left:10px;">Σύμβολο</span><p style="margin:11px;">&nbsp;</p></th>
                        </tr>
            ';

            $index = 0;
            $index2 = 0;
            $class_array = array('even-line', 'odd-line');


            foreach ($this->stations as $station) {
                if($this->createTemplateByRegion($index)==false){
                    $index++;
                }
                else{
                    $html .= '<tr class="'.$class_array[$index2 % 2].'">';
                    $html .= $this->createTemplateByRegion($index++);
                    $html .= "</tr>";
                    $index2++;
                }
            }


            $html .= '
                        </table>
                </body>
                </html>
                        ';
            $template = fopen("/var/www/vhosts/meteokrites.gr/httpdocs/protected/template.html", "w") or die("Unable to open file!");
            fwrite($template, $html);
            fclose($template);
            print $html;
        }

        /**
         * @param $index the index in regions array where our current station data is stored.
         * @return string A html table row representing the template entries of the current station
         */
        private function createTemplateByRegion($index) {
            // Φάκελος
            $folder = $this->stations[$index]['fakelos'];
            // Περιοχή
            $perioxh = $this->stations[$index]['perioxh'];
            // Νομός
            $nomos = $this->stations[$index]['nomos'];
            // Φορέας
            $foreas = $this->stations[$index]['foreas'];
            // url
            $url = $this->stations[$index]['url'];
            // link
            $link = $this->stations[$index]['link'];

            $parse_type = $this->stations[$index]['parse_type'];

            // altitude
            $altitude = $this->stations[$index]['altitude'];

            // downld02.txt data
            $current_forecast_data = $this->parseDownloadFile($folder,$url,$parse_type);

            if($current_forecast_data == false){
                return '';
            }

            if($parse_type==1){
                $date = $current_forecast_data[0];
                $time = $current_forecast_data[1];
                $dew_pt = $current_forecast_data[25];
                $temp_out = $current_forecast_data[6];
                $hum_out = $current_forecast_data[16];
                $wind_speed = $current_forecast_data[35];
                $wind_dir = $current_forecast_data[41];
                $bar = $current_forecast_data[54];
                $rain_rate = $current_forecast_data[70];
                $rain_year = $current_forecast_data[68];    
                $rain_month = $current_forecast_data[67];    
                $rain_day = $current_forecast_data[65];
            }
            else if($parse_type==2){
                $date = $current_forecast_data[0];
                $time = $current_forecast_data[1];
                $dew_pt = $current_forecast_data[14];
                $temp_out = $current_forecast_data[2];
                $hum_out = $current_forecast_data[5];
                $wind_speed = $current_forecast_data[7];
                $wind_dir = $current_forecast_data[9];
                $bar = $current_forecast_data[6];
                $rain_rate = $current_forecast_data[13];
                $rain_year = $current_forecast_data[12];    
                $rain_month = $current_forecast_data[11];    
                $rain_day = $current_forecast_data[10]; 
            }
            else if($parse_type == 4){

                $pieces = explode('/', $current_forecast_data[0]);
                $date = $pieces[0]. '/' . $pieces[1]. '/' . substr($pieces[2],-2);

                $pieces = explode(':', $current_forecast_data[1]);
                $time = $pieces[0] . ':' . $pieces[1];

                $dew_pt = $current_forecast_data[6];
                $temp_out = $current_forecast_data[2];
                $hum_out = $current_forecast_data[5];
                $wind_speed = $current_forecast_data[9];
                $wind_dir = $current_forecast_data[11];
                $bar = $current_forecast_data[8];
                $rain_rate = $current_forecast_data[15];
                $rain_year = $current_forecast_data[14];    
                $rain_month = $current_forecast_data[13];    
                $rain_day = $current_forecast_data[12]; 
            }

            $today = getdate();
            $current_month = $today["mon"];
            $current_day = $today["mday"];
            $date_formatted = date_parse_from_format("d/m/yy", $date);

            // check if time is in h:ia or h:ip format
            if (((strpos($time, 'p')!== false) || (strpos($time, 'a')!== false)) ) {
                $period = $time[strlen($time) - 1];
                $time = substr($time, 0, -1);
                $pos = strpos($time, $period);
                $hour = substr($time,0, strpos($time, ":"));
                $min = substr($time,strpos($time, ":") + 1, strlen($time));

                if ($period === 'a')
                    $hour = (int) $hour + 12;
                $time = $hour.":".$min;
            }
            $to_time = strtotime($time);
            $from_time = strtotime($today["hours"].":".$today['minutes']);
            $diff = round(abs($to_time - $from_time) / 60,2);

            $val1 = $date." " . $time;

       //     $val1 = "28/02/2015 18:00";
            $date1 = DateTime::createFromFormat('d/m/y H:i', $val1, new DateTimeZone('Europe/Athens'));
            $date1->setTimezone(new DateTimeZone('Europe/Athens'));
      //      $current_month = $date1->format('m');
       //     $datetime1 = new DateTime($date);
            $now = new DateTime();
            $now->setTimezone(new DateTimeZone('Europe/Athens'));
            $days = (int) $now->diff($date1)->days;
            $hours = (int) $now->diff($date1)->format("%H");
            // $date1->format(DateTime::ISO8601)
            // ignore the stations that their latest forecast is 2 hour old or more

            $inactive = '';
            $styleforea = ' cssforea';
            if (!(($days == 0) && ($hours < 2) )) {
                $inactive = 'offline';
                $styleforea='';
            }
            //get months and years predictions

            //$rain_month_year = $this->parseYearFile($folder, $date,$url);

            //$rain_month_year[0] = $rain_month_year[0] == '' ? '0.0' : $rain_month_year[0];

            //get today's predictions
            //$rain_day = $this->parseMonthFile($folder,$url);
            $windclass = $wind_speed >= 45 ? " redclass" : "";

            $tempclass = '';
            if(($temp_out >= 35) && ($inactive == '')){
                $tempclass = " redclass";
            }
            else if(($temp_out <= 5) && ($inactive == '')){
                $tempclass = " cold";
            }

            $rainclass='';
            if(($inactive == '') && ($rain_day > 0)){
                $rainclass = " rain";
            }   


            // Σύμβολο
            $icon = "../assets/images/forecast-icons/".ForecastIconsGenerator::getIconPng($temp_out, $rain_rate, $dew_pt, $wind_speed, $bar, $hum_out);

            $html = '
                    <td class="'.$inactive.'">'.$date.'</td>
                    <td class="'.$inactive.'">'.$time.'</td>
                    <td class="'.$inactive.'">'.$nomos.'</td>
                    <td class="'.$inactive.'"><a href="'.$link.'" target="_blank" style="text-decoration:underline;color:#004774;">'.$perioxh.'</a></td>
                    <td class="'.$inactive.'">'.$altitude.'</td>
                    <td class="'.$inactive.$styleforea.'" title="MeteoΚρήτες">'.$foreas.'</td>
                    <td class="'.$inactive.'">'.$rain_year.'</td>
                    <td class="'.$inactive.'">'.$rain_month.'</td>
                    <td class="'.$inactive.$rainclass. '">'.$rain_day.'</td>
                    <td class="'.$inactive.'">'.$bar.'</td>
                    <td class="'.$inactive.$windclass.'">'.$this->convertToBeaufort($wind_speed).'</td>
                    <td class="'.$inactive.'">
                        <img class="arrow" style="-moz-transform:rotate('. $this->getWindDirectionIcon($wind_dir) .'deg);-webkit-transform:rotate('.$this->getWindDirectionIcon($wind_dir).'deg);-ms-transform:rotate('.$this->getWindDirectionIcon($wind_dir).'deg);" src="../assets/images/arrow.png">
                    </td>
                    <td class="'.$inactive.'">'.$hum_out.'%'.'</td>
                    <td class="'.$inactive.$tempclass.'">'.$temp_out.'</td>
                    <td class="'.$inactive.'"><div style="position:relative;margin-left:-9px;"><img src="'.$icon.'" width="75" height="48" ></div></td>
            ';


            return $html;
        }
    }

$template_generator = new TemplateGenerator();
$template_generator->createTemplate();

3 个答案:

答案 0 :(得分:0)

你已经注释掉了$ val1,因此将此变量设置为undefined并导致DateTime返回false。

答案 1 :(得分:0)

首先,您的$ val1已被注释掉,其次是您的日期格式与该值不匹配。

如果您有四位数年份,则必须使用格式中的大写字母Y.

答案 2 :(得分:0)

电话:

DateTime::createFromFormat('d/m/y H:i', $val1, new DateTimeZone('Europe/Athens'));

返回NULL,因为$val1的值为"28/02/2015 18:00"

$val1中的年份以4位数字2015表示,但传递给DateTime::createFromFormat()的格式表明它必须是2位数字(小写 y )。这就是DateTime::createFromFormat()返回NULL

的原因

使用d/m/Y H:i(大写 Y )作为格式,它会起作用。

$val1 = "28/02/2015 18:00";
$date1 = DateTime::createFromFormat('d/m/Y H:i', $val1, new DateTimeZone('Europe/Athens'));

print_r($date1);

输出结果为:

DateTime Object
(
    [date] => 2015-02-28 18:00:00.000000
    [timezone_type] => 3
    [timezone] => Europe/Athens
)