如何用PHP创建返回JSON格式的RESTful WebService(实现GET方法)
Hey there! Let's build a straightforward PHP RESTful Web Service that handles GET requests and spits out JSON—ideal for mobile apps or web apps to consume. Here's a step-by-step breakdown:
Before anything else, we need to make sure our service sends the right headers so clients know they're getting JSON. We'll also handle cross-origin requests (CORS) so mobile/web apps from other domains can call it.
header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Origin: *"); // Adjust this to specific domains in production!
We only want to handle GET requests, so let's check that first and return an error if someone tries to use POST/PUT/DELETE:
if ($_SERVER['REQUEST_METHOD'] !== 'GET') { http_response_code(405); // Method Not Allowed echo json_encode(["error" => "Only GET requests are supported"]); exit; }
For this example, we'll use sample product data, but you can replace this with database queries (using PDO/mysqli for safety) in production. We'll handle two scenarios:
- Fetching all items when no
idparameter is provided - Fetching a single item when an
idis passed via GET
// Sample data (replace with database calls in production) $products = [ ["id" => 1, "name" => "Wireless Headphones", "price" => 99.99], ["id" => 2, "name" => "Smart Watch", "price" => 199.99], ["id" => 3, "name" => "Bluetooth Speaker", "price" => 49.99] ]; $response = []; // Handle single item request if (isset($_GET['id'])) { $productId = intval($_GET['id']); // Sanitize input to prevent issues $foundProduct = null; foreach ($products as $product) { if ($product['id'] === $productId) { $foundProduct = $product; break; } } if ($foundProduct) { http_response_code(200); // OK $response = $foundProduct; } else { http_response_code(404); // Not Found $response = ["error" => "Product not found"]; } } else { // Return all items http_response_code(200); // OK $response = $products; }
Finally, encode our response array into JSON and send it to the client:
echo json_encode($response);
Putting it all together, here's the complete api.php file:
<?php // Set JSON headers and CORS header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Origin: *"); // Restrict to trusted domains in production // Validate request method if ($_SERVER['REQUEST_METHOD'] !== 'GET') { http_response_code(405); echo json_encode(["error" => "Only GET requests are supported"]); exit; } // Sample product data (replace with database logic) $products = [ ["id" => 1, "name" => "Wireless Headphones", "price" => 99.99], ["id" => 2, "name" => "Smart Watch", "price" => 199.99], ["id" => 3, "name" => "Bluetooth Speaker", "price" => 49.99] ]; $response = []; // Handle single product request if (isset($_GET['id'])) { $productId = intval($_GET['id']); $foundProduct = null; foreach ($products as $product) { if ($product['id'] === $productId) { $foundProduct = $product; break; } } if ($foundProduct) { http_response_code(200); $response = $foundProduct; } else { http_response_code(404); $response = ["error" => "Product not found"]; } } else { // Return all products http_response_code(200); $response = $products; } // Output JSON echo json_encode($response); ?>
You can test this using:
- Browser: Visit
http://your-server/api.phpto get all products, orhttp://your-server/api.php?id=1to get the first product. - curl: Run
curl http://your-server/api.phporcurl http://your-server/api.php?id=3in your terminal. - Postman: Send a GET request to the same URLs and check the JSON response.
- CORS: Don't use
Access-Control-Allow-Origin: *in production. Replace it with specific domains likeheader("Access-Control-Allow-Origin: https://your-app-domain.com"). - Input Validation: Always sanitize and validate incoming parameters (like the
idhere) to prevent security issues. - Database Integration: Use PDO or mysqli with prepared statements to interact with your database safely (avoid old mysql_* functions—they're deprecated).
- Error Handling: Add more robust error handling (e.g., catch database exceptions, log errors instead of exposing them to clients).
- Routing: For more complex APIs, consider using a lightweight routing library or writing your own to handle endpoints like
/api/productsand/api/products/{id}.
内容的提问来源于stack exchange,提问作者JB Pakalapati

