PHP包含文件使JSON数据无效 [英] PHP include files are making JSON data invalid

查看:75
本文介绍了PHP包含文件使JSON数据无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对php开发比较陌生,但对Web开发而言却不是.

I'm relatively new to php development but not to web development in general.

我有以下php文件:

<?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));
?>

这将按预期返回JSON数据,但是,如果我将类移至单独的文件并添加include,include_once,require或require_once,它将返回无效的JSON数据.谁能告诉我为什么会这样吗?

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.

谢谢

基思

这是include类,我也尝试过删除?>

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;
    }
}

任何地方都没有前导或尾随空格.这是返回的无效" JSON:

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"}

如果我尝试使用JSONLint对其进行解析,则会给我一个意外令牌". 当然,如果我手动将其键入JSONLint,则可以.我想像有些字符我无法识别/看到显示在JSON中,但是不确定如何找到它.

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.

推荐答案

即使Martin和navnav注释都正确,但是空格通常不会像对二进制格式(例如GIF,JPEG等)那样使Json格式无效. ).

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.).

因此,您的问题可以是 BOM标头许多编辑者都不会使用的2/3字节标头在文件的开头没有显示,或者更糟的是添加.

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.

编辑

删除BOM的一种可能方法是使用和IDE,例如 phpstorm ,该文件具有二进制文件安全的编辑器,能够检测和删除BOM.

A possible way to remove BOM is to use and IDE like phpstorm, having a binary safe editor, able to detect and remove BOM.

这篇关于PHP包含文件使JSON数据无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆