// Set the header of the output header('content-type: application/json; charset=utf-8'); // Create a data object to append onto response $data = [ 'message' => 'Success message', 'status' => 200 ]; // Convert output to JSON format $output = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); // Send the output to the browser echo $output;
// Try to execute a set of codes try { // Throw an exception if an error occurs if (!$conn) { throw new Exception('Connection failed'); } // All code below will not be executed if an error occurs $data = [ 'message' => 'Success message', 'status' => 200 ]; header('content-type: application/json; charset=utf-8'); echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } // Catch an exception if an error occurs catch (Exception $e) { // Display the error message echo 'Error: ' . $e->getMessage(); }Package library: The PHP Exception Library (php-exception-library) In conclusion, there are numerous package libraries in PHP that provide Response models. For instance, Symfony HttpFoundation, GuzzleHttp, Laravel, etc. The selection of the library often depends on framework requirements and development needs.