PHP设置JSON类型HTTP头时出现双Content-Type响应问题
Hey there, let's break down why you're seeing two conflicting Content-Type headers in Postman and how to fix this issue.
The Root Cause
Most likely, PHP is automatically sending a default text/html; charset=UTF-8 header before your custom application/json header gets set. This happens when:
- There's accidental output (like spaces, newlines, or stray HTML) before your
<?phpopening tag. - Your PHP file has a UTF-8 BOM (byte order mark) added by your editor—this invisible character counts as output and triggers header sending.
- You’re using
echo,print, or similar functions anywhere before callingheader().
Once headers are sent (even automatically by PHP), you can’t replace them—you can only add new ones. That’s why you end up with duplicate headers. The true parameter in your second header call only works if the header hasn’t been sent yet.
Quick Fixes to Try
Eliminate Accidental Pre-Output
Double-check your PHP file:- No spaces, newlines, or other characters before the
<?phptag. - Save your file without a UTF-8 BOM (most editors let you set this in save options, like VS Code’s "UTF-8 without BOM").
- Ensure no
echo,print, orvar_dumpcalls run before yourheader()lines.
- No spaces, newlines, or other characters before the
Explicitly Remove Existing Content-Type Headers
Addheader_remove('Content-Type');before setting your custom header to wipe out any auto-generated headers:<?php // Wipe out any existing Content-Type header first header_remove('Content-Type'); // Set the 400 status code header("HTTP/1.1 400 BAD REQUEST"); // Set the correct Content-Type (note no space before the colon!) header("Content-Type: application/json;charset=utf-8", true); // Output your JSON response echo json_encode(['error' => 'Invalid request parameters']); ?>Debug Early Output with
headers_sent()
Use PHP’s built-in function to pinpoint where headers are being sent prematurely:<?php if (headers_sent($file, $line)) { die("Oops! Headers were already sent in $file on line $line"); } // Rest of your header code here ?>This will tell you exactly which file and line is causing the early output.
Fix Header Syntax
While not the main issue, the space before the colon inContent-Type :is non-standard. Remove it to match HTTP header conventions (Content-Type:) and avoid any potential parsing quirks.
Why This Works
By removing pre-existing Content-Type headers before setting your own, you ensure only your application/json header is sent. Fixing pre-output prevents PHP from auto-sending the default text/html header in the first place.
内容的提问来源于stack exchange,提问作者Pandat Arun




