Bonjour,
j'aimerais générer des fichiers json avec php comme ceci
{
"onair":false,
"emission":"Evening Show 2.0",
"titre":"Major Lazer - Lean On",
"listeners":1683
}
mais je ne trouve pas comment faire simplement.
Pouvez-vous m'éclairer?
Merci
Il te suffit simplement de créer un array en php et de l'encoder en JSON avec json_encode :
$json = array(
'Info 1' => 'Contenu 1'
'Info 2' => 'Contenu 2'
...
);
echo json_encode($json);
/* Sortie :
[{"Info 1": "Contenu 1", "info 2": "Contenu 2"}]
*/
Tu peux bien évidemment faire des JSON plus complexes avec des array imbriqués, etc...
En fait json_encode ne transforme pas ta variable, il la convertit et en fait un retour :
// Ici, l'array $json est remplacé par je JSON généré
$json = json_encode($json);
$dir = 'tmp/infos.json';
file_put_contents($dir, $json);
D'accord merci beaucoup, pour le moment je ne pense pas avoir besoin de json complexe ^^
Merci :p
J'ai un problème avec le formattage le json généré me donne ça
falseEvening Show 2.0Headlights (Feat.Ilsey)1
alors qu'en echo il me donne
{"onair":"false","emission":"Evening Show 2.0","titre":"Thinking of You (Video Edit)","listeners":1}
<?php
require_once 'db.php';
$req = $pdo->prepare("SELECT artist, title FROM history WHERE song_type = 0 ORDER BY date_played DESC LIMIT 1");
$pdo->exec("SET CHARACTER SET utf8");
$req->execute();
$song = $req->fetchAll();
$json = array(
'onair' => 'false',
'emission' => 'Evening Show 2.0',
'titre' => $song['0']->title,
'listeners' => 1
);
json_encode($json);
$dir = 'tmp/infos.json';
file_put_contents($dir, $json);