Priya can already call a chat API from PHP, as in Call an AI API from PHP with cURL, and get one string of reminder text. For an email template she needs two fields — a greeting and a body — and she must reject a reply that changes the official balance. A free-form paragraph is hard to trust. A small JSON object is easier to check.
The prompt-engineering lesson showed how to ask for that JSON. This lesson shows how to parse and validate it in PHP: strip the markdown fences models often add, run json_decode, require the keys you asked for, and compare amount_inr with the rupee figure from your own register. We will not hardcode an API key, and we will not let the model invent the amount.
Key takeaways
- Ask the model for JSON only, with named keys such as
greeting,body, andamount_inr. - Models often wrap JSON in markdown fences. Strip them (or slice from the first
{to the last}) beforejson_decode. - Use
json_decode($raw, true), then check that every required key is present and has the right type. - Compare
amount_inrwith the official balance from your own data. Reject a mismatch. - Keep
AI_API_KEYin the environment, and escape any text you print withhtmlspecialchars.
Ask for JSON, not a paragraph
The HTTP call is the same as the cURL lesson: a POST to {base url}/v1/chat/completions. The difference is the instruction. Tell the model the exact shape, and put the official balance in the user message yourself:
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You write short, polite messages for a tuition centre in India. Reply with JSON only, no markdown. Use this shape: {\"greeting\":\"string\",\"body\":\"string\",\"amount_inr\":number}. Copy amount_inr exactly from the user facts. Do not invent amounts or dates."
},
{
"role": "user",
"content": "Write a reminder for Ananya Sharma, who has a balance of ₹1,200 for November tuition. Use amount_inr 1200. Return JSON only."
}
],
"max_tokens": 200
}
A good reply looks like this:
{
"greeting": "Dear parent,",
"body": "Ananya Sharma has a balance of ₹1,200 for November tuition. Kindly pay at the office this week.",
"amount_inr": 1200
}
In practice, the text at choices[0].message.content is not always that clean. Many models wrap the object in a markdown fence (```json … ```). Some add a short sentence before or after the braces. Your PHP should accept the tidy object and still recover the JSON from those messier replies — then validate it.
Extract the JSON, then decode it
<?php
declare(strict_types=1);
function extractJsonString(string $content): string
{
$trimmed = trim($content);
if (preg_match('/^```(?:json)?\s*(.*?)\s*```$/is', $trimmed, $matches)) {
return trim($matches[1]);
}
$start = strpos($trimmed, '{');
$end = strrpos($trimmed, '}');
if ($start !== false && $end !== false && $end > $start) {
return substr($trimmed, $start, $end - $start + 1);
}
return $trimmed;
}
The first branch handles a reply that is only a fenced code block. The second finds the first { and the last }, which covers a short “here is the JSON:” preface. If there is no object at all, json_decode in the next step will fail, and you treat that as an error.
Validate the keys and the official amount
function parseReminderJson(string $content, int $expectedAmount): array
{
$raw = extractJsonString($content);
$data = json_decode($raw, true);
if (!is_array($data)) {
throw new RuntimeException('The model did not return valid JSON.');
}
foreach (['greeting', 'body', 'amount_inr'] as $key) {
if (!array_key_exists($key, $data)) {
throw new RuntimeException('Missing JSON key: ' . $key);
}
}
if (!is_string($data['greeting']) || $data['greeting'] === '' || !is_string($data['body']) || $data['body'] === '') {
throw new RuntimeException('greeting and body must be non-empty strings.');
}
$amount = $data['amount_inr'];
if (is_string($amount) && ctype_digit($amount)) {
$amount = (int) $amount;
}
if (!is_int($amount)) {
throw new RuntimeException('amount_inr must be a whole number of rupees.');
}
if ($amount !== $expectedAmount) {
throw new RuntimeException('amount_inr did not match the official balance.');
}
return [
'greeting' => $data['greeting'],
'body' => $data['body'],
'amount_inr' => $amount,
];
}
Pass true as the second argument to json_decode so you get an associative array, not a stdClass object. Then check the keys yourself. json_decode only asks “is this JSON?”; it does not know that amount_inr must equal 1200.
If the model returns 1500 when the register says 1200, the function throws. That is the behaviour you want. The official figure always comes from your PHP (or from a database, as in the student marks lesson), never from the model.
Put it together with the API call
Build the request in PHP, reuse a cURL helper like the one in the earlier lesson (read the key from AI_API_KEY, POST the JSON, and return choices[0].message.content), then parse the content before you use it:
function buildJsonChatRequest(string $model, string $student, int $balance, string $month, int $maxTokens = 200): array
{
$formatted = number_format($balance);
return [
'model' => $model,
'messages' => [
[
'role' => 'system',
'content' => 'You write short, polite messages for a tuition centre in India. Reply with JSON only, no markdown. Use this shape: {"greeting":"string","body":"string","amount_inr":number}. Copy amount_inr exactly from the user facts. Do not invent amounts or dates.',
],
[
'role' => 'user',
'content' => "Write a reminder for {$student}, who has a balance of ₹{$formatted} for {$month} tuition. Use amount_inr {$balance}. Return JSON only.",
],
],
'max_tokens' => $maxTokens,
];
}
$apiKey = apiKeyFromEnv();
$baseUrl = getenv('AI_API_BASE') ?: 'https://api.openai.com';
$balance = 1200; // rupees; from your register, not from the model
$payload = buildJsonChatRequest(
getenv('AI_MODEL') ?: 'gpt-4o-mini',
'Ananya Sharma',
$balance,
'November'
);
try {
$content = callChatCompletions($baseUrl, $apiKey, $payload);
$reminder = parseReminderJson($content, $balance);
echo htmlspecialchars($reminder['greeting'], ENT_QUOTES, 'UTF-8') . "\n";
echo htmlspecialchars($reminder['body'], ENT_QUOTES, 'UTF-8') . "\n";
} catch (RuntimeException $e) {
http_response_code(502);
echo 'Could not write the reminder just now. Please try again or send it by hand.';
error_log('AI JSON reminder failed: ' . $e->getMessage());
}
The function apiKeyFromEnv and callChatCompletions are the same idea as the cURL lesson: the key stays in the environment, a non-2xx status or a missing content string is an error, and you never echo the key. After a successful parse, htmlspecialchars still applies. JSON from a model is not a trusted source, even when the amount matched.
Try this
First run parseReminderJson on the sample object above, with $expectedAmount = 1200. It should succeed. Change amount_inr to 1500 and run it again; you should get the mismatch error. Then wrap the sample in a ```json fence and confirm it still parses. If you have a local mock or a real compatible endpoint, set AI_API_KEY and AI_API_BASE, switch the student to Rahul Iyer and the balance to ₹2,450, and check that the parsed amount_inr is 2450.
How this was tested
On PHP 8.4, an empty AI_API_KEY raised the missing-key error. parseReminderJson accepted a tidy JSON object and the same object wrapped in a markdown fence or a short preface, and it rejected invalid JSON, a missing body key, and an amount_inr of 1500 when 1200 was expected. The cURL call was pointed at a local mock of POST /v1/chat/completions: a matching Bearer token returned HTTP 200 and JSON that parsed to a ₹1,200 reminder; a wrong token returned HTTP 401 and the function threw API error: Invalid API key. No paid API was called here, so run one live call against your own provider before you rely on it.
What you learned
- Ask the model for a small JSON object with named keys, and put official amounts into the prompt from your own data.
- Strip markdown fences (or slice from
{to}) beforejson_decode($raw, true). - Check required keys, types, and that
amount_inrmatches the official balance. Reject a mismatch. - The API key still belongs in an environment variable. Escape the greeting and body before you print them.
Quick quiz
-
1. Why pass
trueas the second argument tojson_decode?- A) So you get an associative array you can check with
array_key_exists - B) So PHP skips validation of
amount_inr - C) So markdown fences are removed automatically
Show answer
A. The second argument asks for an array, not a
stdClassobject. Fences and amount checks are your job, notjson_decode’s. - A) So you get an associative array you can check with
-
2. The model returns
amount_inr1500, but your register says 1200. What should PHP do?- A) Trust the model and email the parent
- B) Reject the result and treat it as a failure
- C) Average the two figures
Show answer
B. Money is a fact you already have. If the JSON does not copy it exactly, do not use the reply.
-
3. The content is a JSON object wrapped in a
```jsonfence. What should you do first?- A) Pass the whole string, fences included, to
json_decode - B) Strip the fences (or slice from the first
{to the last}), then decode - C) Print the raw content with
echo, without escaping
Show answer
B. Fences are not valid JSON. Remove them, or find the object between the outermost braces, then decode.
- A) Pass the whole string, fences included, to
-
4. Where should
AI_API_KEYbe stored?- A) In a PHP string at the top of the file
- B) In an environment variable, read with
getenv() - C) Inside the JSON you send back to the browser
Show answer
B. A key in the source, or in a response to the browser, can leak. Use
AI_API_KEYor a similar env var.
Related lessons
- Call an AI API from PHP with cURL — the HTTP call this lesson builds on, with the key in the environment.
- Prompt Engineering for Developers: Clear Instructions, Examples and JSON Output — how to ask for the JSON shape you then validate in PHP.
- PHP PDO MySQL Project: Build a Student Marks List — where official figures can come from, if you later connect this reminder to a database.