使用PHP打印JSON对象


Printing JSON object using PHP

我有一个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)"}]

我尝试了以下方法,

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

但它没有起作用:

致命错误:调用第5行/home/dddd.com/public_html/exp.php中未定义的函数var_dup()

有人能帮我理解我做错了什么吗?

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

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

json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)

使用

$json_output = json_decode($json, true);

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

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

试试这个代码:

<?php   
  $jsonurl='http://website.com/international.json'; 
  $json = file_get_contents($jsonurl,0,null,null);  
  $json_output = json_decode($json, true);        
  foreach ($json_output as $trend){         
   echo $trend['text']."'n";     
  } 
?>

谢谢,Dino

$data=[{"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)"}]
$obj = json_decode($data);
$text = $obj[0]->text;

这会奏效的。

json调用中的

JSON_FORCE_OBJECT,例如:

$obj = json_decode($data);

而是这样写:

$obj = json_decode($data, JSON_FORCE_OBJECT);