我在这里有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)
但这没有用,谁能帮助我了解我在做什么错。
<?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)
使用
$json_output = json_decode($json, true);
默认情况下 json_decode 给出 OBJECT 类型,但您尝试将其作为数组访问,因此传递 true 将返回一个数组。
阅读文档:http://php.net/manual/en/function.json-decode.php