Reputation: 3
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.
Upvotes: 0
Views: 2072
Reputation: 4145
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.
Upvotes: 4
Reputation: 3323
Check in your class if there are any whitespace characters before [?php and behind ?]. This would trigger content given to the browser and would create an HTTP Header cannot be created warning, which would give bad JSON.
Check your script - the one you are including this to - also.
It has become somewhat of a "best practice" for many web developers to just don't use ?> for this exact reason.
How does the invalid data look like?
Upvotes: 0
Reputation:
It may be that you're echoing/printing something on the screen in the included files.
JSON doesnt go well with other content.
Also your ?>
tags - are there any lines-breaks/spaces after that tag? If so, there is your problem. Remove them. Infact, if the file will only conatin PHP code, remove the ?>
tag completely as it's not needed.
Upvotes: 2