使用php打印JSON对象

use*_*789 5 php json

我在这里有JSON文件,我想用JSON打印该对象,

JSON格式

[{"text": "Aachen, Germany - Aachen/Merzbruck (AAH)"}, {"text": "Aachen, Germany - Railway (ZIU)"}, {"text": "Aalborg, Denmark - Aalborg (AAL)"}, {"text": "Aalesund, Norway - Vigra (AES)"}, {"text": "Aarhus, Denmark - Aarhus Airport (AAR)"}, {"text": "Aarhus Limo, Denmark - Aarhus Limo (ZBU)"}, {"text": "Aasiaat, Greenland - Aasiaat (JEG)"}, {"text": "Abadan, Iran - Abadan (ABD)"}]
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法,

<?php   
  $jsonurl='http://website.com/international.json'; 
  $json = file_get_contents($jsonurl,0,null,null);  
  $json_output = json_decode($json);        
  foreach ($json_output as $trend)  
  {         
   echo "{$trend->text}\n";     
  } 
?>
Run Code Online (Sandbox Code Playgroud)

但这没有用,谁能帮助我了解我在做什么错。

Mor*_*tgy 5

<?php   

  $jsonurl='http://website.com/international.json'; 
  $json = file_get_contents($jsonurl,0,null,null);  
  $json_output = json_decode($json, JSON_PRETTY_PRINT); 
  echo $json_output;
?>
Run Code Online (Sandbox Code Playgroud)

通过使用JSON_PRETTY_PRINT,您可以将json转换为漂亮的格式,使用json_decode($ json,true)不会将json重新格式化为PRETTY格式的输出,而且您不必在所有键上运行循环即可再次导出同一JSON对象,您可以使用这些常量,也可以在导出之前清除json对象。

json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
Run Code Online (Sandbox Code Playgroud)

  • 虽然这个答案可能是正确且有用的,但如果您[附上一些解释](http://meta.stackexchange.com/q/114762/159034)来解释它如何帮助解决问题,则是首选。如果有变化(可能不相关)导致它停止工作并且用户需要了解它曾经是如何工作的,这在将来会变得特别有用。谢谢! (2认同)

Sum*_*pta 4

使用

$json_output = json_decode($json, true);

默认情况下 json_decode 给出 OBJECT 类型,但您尝试将其作为数组访问,因此传递 true 将返回一个数组。

阅读文档:http://php.net/manual/en/function.json-decode.php