-1

hello i need to write a json file in php, like this. I followed several tutorial but i don't understand how can i put brackets correctly:

{"data": [
    {
        "album": "OK Computer",
        "artist": "Radiohead",
        "first": true,
        "id": "okcomputer",
        "image": "okcomputer.png",
        "tracklist": [
            "Airbag",
            "Paranoid Android",
            "Subterranean Homesick Alien",
            "Exit Music (For a Film)",
            "Let Down",
            "Karma Police",
            "Fitter Happier",
            "Electioneering",
            "Climbing Up the Walls",
            "No Surprises",
            "Lucky",
            "The Tourist"
        ],
        "url": "https://itunes.apple.com/us/album/ok-computer/id696736813?i=696737042&uo=4&at=1l3v7Hz",
        "year": "1997"
    }
]}

how it is possible? Thanks!

  • 2
    Possible duplicate of [Pretty-Printing JSON with PHP](http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php) – wazelin Jun 27 '16 at 12:58
  • just build your php version of the array and then issue a `json_encode($array);` to get the json formatted version of the array. – Lelio Faieta Jun 27 '16 at 13:01

3 Answers3

2

if you define your data as a normal PHP array, then you can use the json_encode function to do this for you. See http://php.net/manual/en/function.json-encode.php

For example:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
ADyson
  • 57,178
  • 14
  • 51
  • 63
0

If you want to store some PHP data in JSON you have to put it into an array, and then use a json_encode function like in your case

$data = array(
'data' => array(
    'album' => 'OK Computer',
    'artist' => 'Radiohead',
    ...
    'tracklist' => array(
        'Airbag',
        'Paranoid Android',
        'Subterranean Homesick Alien',
        'Exit Music (For a Film)',
        'Let Down',
        'Karma Police',
        'Fitter Happier',
        'Electioneering',
        'Climbing Up the Walls',
        'No Surprises',
        'Lucky',
        'The Tourist'),
    'url' => 'http://somesite',
    'year' => '1997')
);

$json = json_encode($data);
baskax
  • 233
  • 3
  • 11
  • close, but `'data'=>array(array(`, also, it is probably more readable to use short array syntax in php, as it looks the same as json: `'data'=>[[` – Steve Jun 27 '16 at 13:05
0

try this one

<?php
$output=array();
$data=array();
$item=array();
$item['album']="OK Computer";
$item['other']="same as album";
$tracklist=array('a','b','c');
$item['tracklist']=$tracklist;
array_push($data,$item);
$output['data']=$data;
echo json_encode($output);
?>

output:

{
    "data": [{
        "album": "OK Computer",
        "other": "same as album",
        "tracklist": ["a", "b", "c"]
    }]
}
sharif2008
  • 2,716
  • 3
  • 20
  • 34