r/PHPhelp • u/Friendly_Nothing_546 • Dec 01 '25
Json encode dando header already sent
Hello, I'm developing a simple CRUD project with PHP, in the part I deliver a Json to the frontend and it displays the data, the Json goes with all the fields as mentioned and the error header already sent the source code of this specific part is this
<?php namespace App\Controller; use App\config\Database; use App\controller\LoginController; use function App\src\connect; if(session_status() === PHP_SESSION_NONE) { session_start(); } class adminController { public function admin() { require __DIR__ . '/../../public/Pagina-adm/admin (1).html'; $pdo = connect(); $sec_control = new LoginController(); $controller = new Database(); $view = $controller->search_id($pdo, "administrator", "adm_id", $_SESSION["adm_id"]); $key = $controller -> fetch_key($pdo, "adm_key", $_SESSION["adm_id"], "adm_id"); header('Content-Type: application/json'); $data = array( 'name' => $sec_control -> decrypt($view['name'], $key['crypto_key']), 'email' => $sec_control -> decrypt($view['email'], $key['chave_crypto']), 'telephone' => $sec_control -> decrypt($view['telefone'], $key['crypto_key']), ); echo json_encode($data); } Does anyone know how to solve it?
2
u/Big-Dragonfly-3700 Dec 01 '25 edited Dec 01 '25
The error message states where the output is occurring at - (output started at ...) that is preventing the header() from working.
The problem is most likely because you are requiring a .html file before the header() statement. You cannot output any text/html before the header. When you output json encoded data as a response, you do not output any of the html document with it.
8
u/colshrapnel Dec 01 '25
You need to pay more attention to the error message you get. Often, it contains much more information than just error statement. For example, this particular error message, beside just naming the error, also provides two critically important parts: the place where the error occurred AND also the place, where unwanted output had started.
From this information you will learn that json_encode is unrelated to this problem and will have check the code that starts unwanted output.
Besides, it's always a good idea to check existing questions from people with similar problem. Usually, Stack Overflow has a detailed explanation that should make you able to fix this error with ease
4
u/thmsbrss Dec 01 '25
(Source code) formatting is your friend.