Hi,

I have a PHP which should return json output. I am using the same code in other application and it works fine but now getting:

headers already sent

This is my code.. Kindly help..

<?php
  header("Content-Type: application/json");

  if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }

$mysql_host		=	"mysql:host=mysql.mydomain.com;dbname=myDB";
$mysql_user		=	"mydomainuser";
$mysql_password	=	"mydomainPassword";
$mysql_options 	=	array
					(
						PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
					);

// $mysql_connection;
$mysql_connection = new PDO($mysql_host, $mysql_user, $mysql_password, $mysql_options);
$mysql_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $mysql_query = $mysql_connection->prepare('CALL sp_populate_countries()');
	$mysql_query->execute();

  if ($mysql_query->rowCount() <= 0) { echo "false"; }
  else
  {
    $jsonData = '{ "Countries" :[';

while($mysql_row = $mysql_query->fetch())
{
  $jsonData .= '{"country_code_alpha2":"' . $mysql_row["country_code_alpha2"] . '","country_name":"' . $mysql_row["country_name"] . '"},';
}

$jsonData = chop($jsonData, ",");
$jsonData .= ']}';

	echo $jsonData;
  }
?>

Jassim

    What does the error message say, exactly? Namely, at what file/line-number does it say headers were already sent?

    One not uncommon gotcha is a BOM (Byte Order Mark) at the start of the file before the <?php tag, if your editor saved the file as UTF-8 with BOM (in which case there should be an option to save it without BOM).

      There's also a possibility - if this file is being included from a different script - that there's white space after a closing php ( ?> ) tag. You don't need the closing tags on files, and you'll avoid the possibility of this issue if you don't use them.

        maxxd;11060581 wrote:

        There's also a possibility - if this file is being included from a different script - that there's white space after a closing php ( ?> ) tag. You don't need the closing tags on files, and you'll avoid the possibility of this issue if you don't use them.

        +1 🙂

          Write a Reply...