Level 16
Hi, Did you find any solution for this problem?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
<?php
$openAiResponse = <<<JSON
{
"ai_response": "• Review the scope of work and sequence of job steps. Confirm everyone understands their roles and responsibilities.
• For the jackhammering task, ensure the operator is trained and competent. Discuss potential hazards like silica dust, noise, and flying debris. Use water suppression and barricade the area. Wear proper PPE including respirators, hearing protection, and eye protection.
• When tying rebar, inspect materials for defects before rigging and lifting. Use proper lifting techniques, keep fingers clear of pinch points, and take measures to prevent impalement hazards. Wear cut-resistant gloves.
• For formwork, inspect materials and braces. Set up work zone protections for leading edges and openings. Use caution when working at height. Attach forms securely and plumb walls frequently. Wear fall protection when required.
• Ask if anyone has concerns about today's work or safety conditions. Emphasize the importance of speaking up if something seems unsafe at any point. Confirm there is adequate access to first aid and emergency procedures are understood if needed."
}
JSON;
$placeholder = "[[NEWLINE]]";
$convertedResponse = str_replace(["\r\n", "\n", "\r"], $placeholder, $openAiResponse);
// Clean the string of unwanted control characters but exclude the newline characters
$cleanedResponse = preg_replace('/[[:cntrl:]](?!\r\n)/', '', $convertedResponse);
// Restore the newlines from the placeholder
$finalResponse = str_replace($placeholder, "\n", $cleanedResponse);
$decoded = json_decode($finalResponse, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo ('JSON Decode Error after cleaning: ' . json_last_error_msg());
} else {
echo ('Decoded Response after cleaning: ' . json_encode($decoded));
}
I am trying to json decode these texts, however , I am getting this error: Control character error, possibly incorrectly encoded. By the way, these texts could be different, all I want is to dispay text correctly and also show the new line character correctly that means each bullet points should be in new line if there are any.
Please or to participate in this conversation.