php 8.6可通过opis json schema 2.x按本地固定schema校验json结构,再将字段路径和错误消息作为json返回。先安装opis/json-schema:^2并执行composer平台检查;schema由服务端控制,不接受用户传入远端引用或自定义schema。

Opis官方文档中的Validator
把JSON对象与本地规则交给验证器
<?php
require __DIR__.'/vendor/autoload.php';
use Opis\JsonSchema\CompliantValidator;
use Opis\JsonSchema\Errors\ErrorFormatter;
$raw=file_get_contents('php://input',false,null,0,65537);
header('Content-Type: application/json; charset=utf-8');
if (!is_string($raw) || strlen($raw)>65536) {http_response_code(413);exit;}
try { $data=json_decode($raw,false,32,JSON_THROW_ON_ERROR); }
catch (JsonException $e) {http_response_code(400);echo '{"error":"invalid_json"}';exit;}
$schema=json_decode(<<<'JSON'
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object",
"required":["name","quantity"],"additionalProperties":false,
"properties":{"name":{"type":"string","minLength":1,"maxLength":80},
"quantity":{"type":"integer","minimum":1,"maximum":100}}}
JSON,false,32,JSON_THROW_ON_ERROR);
$result=(new CompliantValidator())->validate($data,$schema);
if (!$result->isValid()) {
http_response_code(422);
echo json_encode(['errors'=>(new ErrorFormatter())->format($result->error())],
JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE);exit;
}
echo '{"valid":true}';
Opis官方文档中的Error formatter
区分语法错误和结构错误
破损JSON返回400;语法正确但quantity为字符串、超出范围或出现未知属性时返回422。对象保持stdClass表示,避免将空对象与空数组混为一种PHP数组。内容类型、认证与业务权限仍由路由层检查。
exa-js 是 Exa 官方 JavaScript 软件开发工具包,Exa 是一个为 AI 工作流构建的网络搜索 API。它为代理提供了一种具体的方式来搜索网络、检索页面内容,并从代码中生成有来源的答案,而不是手动拼接原始 HTTP 调用。
保持Schema加载可控
示例没有配置网络加载器,固定规则也不含外部$ref。错误格式化默认不意味着返回全部可能错误;需要多错误结果时,按验证器max errors及stop at first error配置重新评估。规则合法性等程序配置异常属于服务端问题,不向客户端输出堆栈或内部文件位置。


















