I’m creating a JSON string from the results of a mySQL query in PHP. But for some reason the PHP “header” function isn’t appending anything when I save the results to a file for sanity checks. Below is the code:
header("Content-Type: application/json");
if(mysql_num_rows($result)){
$dataResults = '{"Data":[';
$first = true;
$row = mysql_fetch_assoc($result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
if($first) {
$first = false;
} else {
$dataResults = $dataResults . ',';
}
$dataResults = $dataResults . json_encode($row);
}
$dataResults = $dataResults . ']}';
} else {
$dataResults = '[]';
}
file_put_contents('/Applications/MAMP/htdocs/PHP/results.json', $dataResults);
The output looks o.k., except it is missing the “Content-Type: application/json”. What am I doing wrong?
Why would
header()write anything to the file?header()sets response header information using the response hook inmod_phpor whatever the CGI equivalent is if using CGI.Text files do not contain any meta information other than their encoding (if that).