2014-12-27 136 views
-1

我终于确定我的JSON对象滑过了一个JSON验证器。但是,当我尝试解码它返回null。我的JSON对象看起来像以下:php JSON对象返回null

[ 
    { 
     "NAME": "Hearthstone", 
     "PLAYER1": "Rdu ", 
     "PLAYER2": "Savjz ", 
     "status": 2, 
     "meta": "LIVE" 
    }, 
    { 
     "NAME": "LeagueofLegends", 
     "PLAYER1": "TeamKing", 
     "PLAYER2": "EDG", 
     "status": 2, 
     "meta": "28.12." 
    } 
] 

PHP解码:

$json = file_get_contents("crawl_JSON.php"); 
$json_output = json_decode($json); 

var_dump($json_output); 
+1

确保'crawl_JSON.php'在JSON之前或之后不输出任何内容。 – Barmar 2014-12-27 19:00:45

+0

'var_dump($ json)' – 2014-12-27 19:00:59

+1

在上一个问题中,您是否被问过产生一个最简单的例子?请每次都这样做,这不会有帮助。 – 2014-12-27 19:06:00

回答

2

在你的PHP文件解码,你跟<??>周边呢?

当我尝试时,它为我工作。我假设你的JSON文件名为crawl_JSON.php,它与你正在执行PHP文件的目录相同?否则,您可能需要指定完整路径。

从我的文件的更多细节:

crawl_JSON.php:

[ 
    { 
     "NAME": "Hearthstone", 
     "PLAYER1": "Rdu ", 
     "PLAYER2": "Savjz ", 
     "status": 2, 
     "meta": "LIVE" 
    }, 
    { 
     "NAME": "LeagueofLegends", 
     "PLAYER1": "TeamKing", 
     "PLAYER2": "EDG", 
     "status": 2, 
     "meta": "28.12." 
    } 
] 

test.php的:

<? 
$json = file_get_contents("crawl_JSON.php"); 
$json_output = json_decode($json); 

var_dump($json_output); 
?> 

而且从执行程序我的输出:

Marks-MacBook-Pro:stackOverflow mmadej$ php -f test.php 
array(2) { 
    [0]=> 
    object(stdClass)#1 (5) { 
    ["NAME"]=> 
    string(11) "Hearthstone" 
    ["PLAYER1"]=> 
    string(4) "Rdu " 
    ["PLAYER2"]=> 
    string(6) "Savjz " 
    ["status"]=> 
    int(2) 
    ["meta"]=> 
    string(4) "LIVE" 
    } 
    [1]=> 
    object(stdClass)#2 (5) { 
    ["NAME"]=> 
    string(15) "LeagueofLegends" 
    ["PLAYER1"]=> 
    string(8) "TeamKing" 
    ["PLAYER2"]=> 
    string(3) "EDG" 
    ["status"]=> 
    int(2) 
    ["meta"]=> 
    string(6) "28.12." 
    } 
} 
+0

为什么JSON文件不是PHP脚本时会命名为'.php'?这太疯狂了。更可能的是它实际上是一个运行时输出JSON的PHP脚本,所以Barmar的回答是正确的。 – 2014-12-27 19:19:46

+0

@LightnessRacesinOrbit在之前的一个问题中,OP在一些评论中展示了如何用PHP数组构建它,我不得不承认Post不完整 – meda 2014-12-27 19:26:38

+0

我的猜测是他只是一个新的编码器,并且可能不知道正确的方法一切。否则,他可能不会在这里提出一个相对简单的问题。我认为crawl_JSON.php显然是一个基于内容的JSON文件(而不是PHP)。 – 2014-12-27 19:28:06

2

PHP脚本未运行如果您以普通文件的形式访问它们,则必须通过网络服务器访问它们。因此,将其更改为:

$json = file_get_contents("http://localhost/crawl_JSON.php"); 

这假定脚本在文档根目录,你可能需要从文档根目录添加到脚本的完整路径。