You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

Step 1: Set Up Response Headers First

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!
Step 2: Validate the Request Method

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;
}
Step 3: Add Your Data Logic (Sample or Database)

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 id parameter is provided
  • Fetching a single item when an id is 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;
}
Step 4: Output the JSON Response

Finally, encode our response array into JSON and send it to the client:

echo json_encode($response);
Full Working Example

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);
?>
Testing the Service

You can test this using:

  • Browser: Visit http://your-server/api.php to get all products, or http://your-server/api.php?id=1 to get the first product.
  • curl: Run curl http://your-server/api.php or curl http://your-server/api.php?id=3 in your terminal.
  • Postman: Send a GET request to the same URLs and check the JSON response.
Production Tips
  • CORS: Don't use Access-Control-Allow-Origin: * in production. Replace it with specific domains like header("Access-Control-Allow-Origin: https://your-app-domain.com").
  • Input Validation: Always sanitize and validate incoming parameters (like the id here) 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/products and /api/products/{id}.

内容的提问来源于stack exchange,提问作者JB Pakalapati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:48:30