Print JSON object using php

Here I have a JSON file, I would like to print this object in JSON format,

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)"}] 

I tried the following way,

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

but it didn’t work, can someone help me understand what I am doing wrong.

+4
source share
4 answers
 <?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; ?> 

using JSON_PRETTY_PRINT you will convert your json to beautiful formatting, using json_decode ($ json, true) do not reformat the json output to PRETTY, and you don’t need to run a loop over all the keys to export the same JSON object again, you can also use those constants that could clear your JSON object before exporting it.

 json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) 
+5
source

use

$json_output = json_decode($json, true);

json_decode provides an OBJECT type by default, but you are trying to access it as an Array, so passing true will return an array.

Read the documentation: http://php.net/manual/en/function.json-decode.php

+3
source

Try this code:

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

Thanks Dino

0
source
 $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; 

This will work.

0
source

Source: https://habr.com/ru/post/1488031/


All Articles