如何修复PHP 8.0上的数组生成函数返回错误500,但它在PHP 7.4上工作得很好,我试图检查控制台,它返回值1

gopyfrb3  于 2023-04-10  发布在  PHP
关注(0)|答案(1)|浏览(138)

这个函数在PHP 7.4上运行良好,但是当我将服务器更新到php 8.1时,我得到了错误500内部服务器错误。请帮助

public function getTicketJsonBYNumber($mobile_number = null)<br />
        {<br />
            $this->load->model(array('website_model'));<br />
            $booking_id_no = $this->website_model->getBookingIDByNumber($mobile_number);<br />
            $ticket = $this->website_model->getPaidTicket($booking_id_no);  <br />
            $data = array(<br />
                'pickup_trip_location' => $ticket->pickup_trip_location,<br />
                'drop_trip_location'   => $ticket->drop_trip_location,<br />
                'passenger_name'       => $ticket->passenger_name,<br />
                );<br />
                $this->output->set_header('Access-Control-Allow-Methods: GET');<br />
               $this->output->set_header('Access-Control-Allow-Origin: *');<br />
               $this->output<br />
                 ->set_content_type('application/json')<br />
                 ->set_output(json_encode($data));<br />
        }
f2uvfpb9

f2uvfpb91#

在PHP 8.0中,json_encode()现在在遇到错误时返回false而不是空字符串,这可能会导致内部错误,为了修复它,请在PHP函数中添加适当的错误处理,我已经为您添加了它,这应该在PHP 8.0中正常工作。

public function getTicketJsonBYNumber($mobile_number = null)
{
    $this->load->model(array('website_model'));
    $booking_id_no = $this->website_model->getBookingIDByNumber($mobile_number);
    $ticket = $this->website_model->getPaidTicket($booking_id_no);
    $data = array(
        'pickup_trip_location' => $ticket->pickup_trip_location,
        'drop_trip_location'   => $ticket->drop_trip_location,
        'passenger_name'       => $ticket->passenger_name,
    );
    $this->output->set_header('Access-Control-Allow-Methods: GET');
    $this->output->set_header('Access-Control-Allow-Origin: *');
    $json_data = json_encode($data);
    if ($json_data === false) {
        // handle error, e.g. log the error message
        error_log('JSON encoding error: ' . json_last_error_msg());
        // return an error message to the client
        $this->output
            ->set_status_header(500)
            ->set_content_type('application/json')
            ->set_output(json_encode(array('error' => 'JSON encoding error')));
    } else {
        $this->output
            ->set_content_type('application/json')
            ->set_output($json_data);
    }
}

相关问题