使用 PHP 抛出正确的 HTTP 标头


Throw correct HTTP header with PHP

使用我正在制作的网络服务,用户可以通过在URI中输入ID来转到"详细信息"页面。

到目前为止,我能够使用以下代码从给定的 Id 中获取数据

$id = $_GET['id'];
        $file = file_get_contents("data.json");
        $json = json_decode($file);

        foreach ($json->items as $item) {
            if ($item->id == $id) {
                $json = json_encode($item);
                $header = $_SERVER['HTTP_ACCEPT'];
                switch ($header) {
                    case "application/json":
                        header('Content-Type: application/json');
                        echo $json;
                        break;
                    case "application/xml":
                        header('Content-type: application/xml');
                        $serializer = &new XML_Serializer();
                        $obj = json_decode($json);
                        if ($serializer->serialize($obj)) {
                            echo $serializer->getSerializedData();
                        } else {
                            return null;
                        }
                        break;
                    default:
                        header('HTTP/1.1 415 Unsupported Media Type');
                        echo json_encode(["message" => "Unsupported format. Choose JSON or XML"]);
                        break;
                }
            }
        }

现在我的问题是,当用户输入不在 JSON 文件中的 ID 时,我仍然返回 200 OK。当找到 Id(以及一些数据)时,我想返回 200 OK,当在 JSON 中找不到输入的 Id 时,我想返回 404 未找到。

关于我该怎么做的任何想法?

$id = $_GET['id'];
        $file = file_get_contents("data.json");
        $json = json_decode($file);
$item = null;
foreach ($json->items as $tmp) {
 if ($tmp->id == $id) {
   $item = $tmp;
   break;
 }
}
if ($item == null) {
  header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
} else {
  // your own code you used above.
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
 $json = json_encode($item);
                $header = $_SERVER['HTTP_ACCEPT'];
                switch ($header) {
                    case "application/json":
                        header('Content-Type: application/json');
                        echo $json;
                        break;
                    case "application/xml":
                        header('Content-type: application/xml');
                        $serializer = &new XML_Serializer();
                        $obj = json_decode($json);
                        if ($serializer->serialize($obj)) {
                            echo $serializer->getSerializedData();
                        } else {
                            return null;
                        }
                        break;
                    default:
                        header('HTTP/1.1 415 Unsupported Media Type');
                        echo json_encode(["message" => "Unsupported format. Choose JSON or XML"]);
                        break;
                }
}