2012-11-29 110 views
3

我有这样的代码:如何从PHP文件输出格式正确的JSON?

<?php 

    header('Content-Type: text/javascript; charset=UTF-8'); 
    header('Cache-Control: private, no-cache, no-store, must-revalidate'); 
    header('Pragma: no-cache'); 
    header('Expires: Sat, 01 Jan 2000 00:00:00 GMT'); 

    $data = array(
     "data" => array(
      "sender" => "Jhon Andrew", 
      "recipient" => "Someone OverThe Internet", 
      "conversation" => 
      array(
       "unix" => "1234567890", 
       "message" => "Lorem ipsum dolor sit amet." 
      ), 
      array(
       "unix" => "0987654321", 
       "message" => "Tema tis rolod muspi merol." 
      ) 
     ) 
    ); 

    echo json_encode($data); 

?> 

而且我期待这样的结果:

{ 
    "data": { 
     "sender":"Jhon Andrew", 
     "recipient":"Someone OverThe Internet", 
     "message":"Lorem ipsum dolor sit amet." 
    } 
} 

但我把它显示在只有一条线路,这样的:

{"data":{"sender":"Jhon Andrew","recipient":"Someone OverThe Internet","message":"Lorem ipsum dolor sit amet."}} 

我如何才能正确格式化JSON输出,就像我期待的那样?实际上这并不重要,但我只想看到格式良好的结果。


...顺便说一下,我只是复制Facebook的从图形链接 头,因为这就是我想要的输出结果。例如: graph.facebook.com/mOngsAng.gA


它是有效,当然。所有我想知道的是如何输出它像 这个:graph.facebook.com/mOngsAng.gA - 正如你可以看到它正确格式化 。我的意思是它有断线和凹痕。不像我是 得到只是在一行中显示。

+0

...顺便说一句,我只是从脸谱图链接复制头,因为这是我想输出结果。例如:http://graph.facebook.com/mOngsAng.gA –

+0

您是否尝试使用PHP的'json_encode()'函数? –

+0

@ parker.sikand是的,我做到了。正如你在我展示的PHP代码中看到的那样。 –

回答

4

看看JSON_PRETTY_PRINT标志json_encode()在PHP手册。 您可以简单地使用:

$data = json_encode($data, JSON_PRETTY_PRINT); 

如果你不使用PHP 5.4或更大的尝试与问题的接受的答案:Pretty-Printing JSON with PHP

但是,你的是有效的 json输出!

+0

这只是我需要但是我得到一个错误,也许因为我的PHP版本。我现在正在阅读你给的链接。 –

+0

非常感谢!我现在有我的预期结果。我刚使用了这个PHP函数:http://recursive-design.com/blog/2008/03/11/format-json-with-php/ - 因为我使用PHP版本低于5.4 |对于人们来说,我的问题和使用PHP 5.4+的“JSON_PRETTY_PRINT”相同。再次感谢! :] –

+0

不客气! :) – jan267