I’m relatively new to php development but not to web development in general.
I have the following php file:
<?php
class dialogResult{
var $Message;
var $Title;
var $Height;
var $GenericData;
function __construct(){
$this->Height = 10;
}
}
header("Cache-Control: no-cache", true);
header("Content-type: application/json; charset=utf-8", true);
$dr = new dialogResult();
$dr->Message = "A Test Message encoded";
$dr->Height = 10;
$dr->GenericData = "Empty";
$dr->Title = "My Message";
echo(json_encode($dr));
?>
This returns JSON data as expected, however if I move the class to a separate file and add an include, include_once, require, or require_once it returns invalid JSON data. Can anyone tell me why this would be?
It doesn’t have to be just moving this class, if I have ANY included file it makes the data invalid.
Thanks,
Keith
Here is the include class, I’ve also tried removing the ?>
<?php
class dialogResult{
var $Message;
var $Title;
var $Height;
var $GenericData;
function __construct(){
$this->Height = 10;
}
}
There are no leading or trailing spaces anywhere. Here is the ‘invalid’ JSON that is returned:
{"Message":"A Test Message encoded","Title":"My Message","Height":10,"GenericData":"Empty"}
which gives me an “Unexpected Token” if I try to use JSONLint to Parse it.
Of course, if I type it in by hand to JSONLint then it is fine. I imagine there is some character I can’t identify/see showing up in the JSON but am not sure how to find it.
Even Martin and navnav comments are right, but whitespaces usually don’t invalid the Json format as they can do with binary formats (eg. GIF, JPEG, etc.).
So your problema can be the BOM header a 2/3 byte header that many editors don’t show or, worse, add, at the beginning of the file.
EDIT
A possible way to remove BOM is to use and IDE like phpstorm, having a binary safe editor, able to detect and remove BOM.