Reputation: 566
I have a JSON file and I would like to print that object in 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)"}]
I have tried with following method,
<?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:
Fatal error: Call to undefined function var_dup() in /home/dddd.com/public_html/exp.php on line 5
Can anyone help me understand what I'm doing wrong?
Upvotes: 6
Views: 69877
Reputation: 1
JSON_FORCE_OBJECT
in your json call eg :
$obj = json_decode($data);
Instead write like this:
$obj = json_decode($data, JSON_FORCE_OBJECT);
Upvotes: 0
Reputation: 563
<?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;
?>
by using JSON_PRETTY_PRINT u transform your json to pretty formatting, using json_decode($json, true) doesn't reformat your json to PRETTY formatted output, also you don't have to run loop over all keys to export same JSON object again, you could use those constants also which could clean up your json object before exporting it.
json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
Upvotes: 7
Reputation: 1
$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.
Upvotes: 0
Reputation: 1401
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
Upvotes: 0
Reputation: 2192
use
$json_output = json_decode($json, true);
by default json_decode give OBJECT type but you are trying to access it as Array, so passing true will return an array.
Read documentation : http://php.net/manual/en/function.json-decode.php
Upvotes: 4