Manipuler JSON avec PHP¶
Le format JSON aujourd’hui massivement utilisé dans le Web, en particulier dans les services Web, comme format d’échange entre les serveurs et les clients Web ou entre serveurs et applications mobiles. C’est un format natif en JavaScript en effet JSON veut dire JavaScript Object Notation.
Sa manipulation dans un langage comme PHP est très simple.
Ecrire et lire du JSON en PHP¶
Encodage JSON à partir d’un tableau PHP, puis décodage JSON¶
<?php
$programmes = array(
array("nom"=> "Simpsons","chaine" => "TF18","debut" => "21:00","duree" => "30"),
array("nom" => "Blake et Mortimer","chaine" => "M54","debut" => "20:00","duree" =>"60")
);
print(json_encode($programmes, JSON_PRETTY_PRINT));
Exécution :¶
Resultat brut html :¶
[
{
"nom": "Simpsons",
"chaine": "TF18",
"debut": "21:00",
"duree": "30"
},
{
"nom": "Blake et Mortimer",
"chaine": "M54",
"debut": "20:00",
"duree": "60"
}
]
Encodage JSON à partir d’une BD¶
Si on récupère des données de la table CARNET pour les exporter en JSON :
<?php
require_once('connexion.php');
$connexion=connect_bd();
$sql="SELECT * from CARNET";
$data=$connexion->query($sql);
$contacts=array();
//while($pers=$data->fetch(PDO::FETCH_OBJ)){
while($pers=$data->fetch(PDO::FETCH_ASSOC)){
$contacts[]=$pers;
}
//print_r($contacts);
$json = json_encode($contacts, JSON_PRETTY_PRINT);
echo 'json :<br>'.PHP_EOL;
print($json);
#echo '<br>'.PHP_EOL;
#echo 'décodage du json : <br>'.PHP_EOL;
#print_r(json_decode($json, true));
Exécution :¶
Resultat brut html :¶
json :<br>
[
{
"ID": 1,
"NOM": "SMITH",
"PRENOM": "JOHN",
"NAISSANCE": "1980-12-17",
"VILLE": "ORLEANS"
},
{
"ID": 2,
"NOM": "DURAND",
"PRENOM": "JEAN",
"NAISSANCE": "1983-01-13",
"VILLE": "ORLEANS"
},
{
"ID": 3,
"NOM": "GUDULE",
"PRENOM": "JEANNE",
"NAISSANCE": "1967-11-06",
"VILLE": "TOURS"
},
{
"ID": 4,
"NOM": "ZAPATA",
"PRENOM": "EMILIO",
"NAISSANCE": "1956-12-01",
"VILLE": "ORLEANS"
},
{
"ID": 5,
"NOM": "JOURDAIN",
"PRENOM": "NICOLAS",
"NAISSANCE": "2000-09-10",
"VILLE": "TOURS"
},
{
"ID": 6,
"NOM": "DUPUY",
"PRENOM": "MARIE",
"NAISSANCE": "1986-01-11",
"VILLE": "BLOIS"
},
{
"ID": 7,
"NOM": "ANDREA",
"PRENOM": "LOU",
"NAISSANCE": "1900-01-01",
"VILLE": "BLOIS"
},
{
"ID": 9,
"NOM": "Kafka",
"PRENOM": "Le Bon",
"NAISSANCE": "2003-12-06",
"VILLE": "Prague"
},
{
"ID": 11,
"NOM": "Dalton",
"PRENOM": "Joe",
"NAISSANCE": "2003-12-06",
"VILLE": "Dallas"
},
{
"ID": 12,
"NOM": "Kafkad",
"PRENOM": "Franz",
"NAISSANCE": "1992-06-22",
"VILLE": "Prague"
}
]
En changeant le nom des clefs dans le JSON¶
On peut modifier au passage le nom des clefs que l’on souhaite utiliser dans le JSON :
<?php
require_once('connexion.php');
$connexion=connect_bd();
$sql="SELECT * from CARNET";
$data=$connexion->query($sql);
$contacts=array();
while($pers=$data->fetch()){
$contacts[]=array(
'nom'=>$pers['NOM'],
'prenom'=>$pers['PRENOM'],
'naissance'=>$pers['NAISSANCE']);
}
$json=json_encode($contacts, JSON_PRETTY_PRINT);
print($json);
Exécution :¶
Resultat brut html :¶
[
{
"nom": "SMITH",
"prenom": "JOHN",
"naissance": "1980-12-17"
},
{
"nom": "DURAND",
"prenom": "JEAN",
"naissance": "1983-01-13"
},
{
"nom": "GUDULE",
"prenom": "JEANNE",
"naissance": "1967-11-06"
},
{
"nom": "ZAPATA",
"prenom": "EMILIO",
"naissance": "1956-12-01"
},
{
"nom": "JOURDAIN",
"prenom": "NICOLAS",
"naissance": "2000-09-10"
},
{
"nom": "DUPUY",
"prenom": "MARIE",
"naissance": "1986-01-11"
},
{
"nom": "ANDREA",
"prenom": "LOU",
"naissance": "1900-01-01"
},
{
"nom": "Kafka",
"prenom": "Le Bon",
"naissance": "2003-12-06"
},
{
"nom": "Dalton",
"prenom": "Joe",
"naissance": "2003-12-06"
},
{
"nom": "Kafkad",
"prenom": "Franz",
"naissance": "1992-06-22"
}
]
En une seule passe¶
Ecriture de JSON en une seule passe en utilisant des données provenant d’une Base de Données.
<?php
require_once('connexion.php');
$connexion = connect_bd();
$sql = "SELECT * from CARNET";
$data = $connexion->query($sql);
$contacts = $data->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($contacts, JSON_PRETTY_PRINT);
print($json);
Exécution :¶
Resultat brut html :¶
[
{
"ID": 1,
"NOM": "SMITH",
"PRENOM": "JOHN",
"NAISSANCE": "1980-12-17",
"VILLE": "ORLEANS"
},
{
"ID": 2,
"NOM": "DURAND",
"PRENOM": "JEAN",
"NAISSANCE": "1983-01-13",
"VILLE": "ORLEANS"
},
{
"ID": 3,
"NOM": "GUDULE",
"PRENOM": "JEANNE",
"NAISSANCE": "1967-11-06",
"VILLE": "TOURS"
},
{
"ID": 4,
"NOM": "ZAPATA",
"PRENOM": "EMILIO",
"NAISSANCE": "1956-12-01",
"VILLE": "ORLEANS"
},
{
"ID": 5,
"NOM": "JOURDAIN",
"PRENOM": "NICOLAS",
"NAISSANCE": "2000-09-10",
"VILLE": "TOURS"
},
{
"ID": 6,
"NOM": "DUPUY",
"PRENOM": "MARIE",
"NAISSANCE": "1986-01-11",
"VILLE": "BLOIS"
},
{
"ID": 7,
"NOM": "ANDREA",
"PRENOM": "LOU",
"NAISSANCE": "1900-01-01",
"VILLE": "BLOIS"
},
{
"ID": 9,
"NOM": "Kafka",
"PRENOM": "Le Bon",
"NAISSANCE": "2003-12-06",
"VILLE": "Prague"
},
{
"ID": 11,
"NOM": "Dalton",
"PRENOM": "Joe",
"NAISSANCE": "2003-12-06",
"VILLE": "Dallas"
},
{
"ID": 12,
"NOM": "Kafkad",
"PRENOM": "Franz",
"NAISSANCE": "1992-06-22",
"VILLE": "Prague"
}
]
Se connecter à une API pour récupérer du JSON¶
On peut créer une clef d’API sur OpenWeatherMap, puis se connecter à l’API correspondante pour y lire la météo d’un lieu :
<?php
require_once('api-key.php');
$city = "Yakutsk";
$apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=" . $city . "&units=metric&APPID=" . API_KEY;
$response = file_get_contents($apiUrl, False);
$data = json_decode($response);
print_r($data);
Exécution :¶
Resultat brut html :¶
stdClass Object
(
[coord] => stdClass Object
(
[lon] => 129.7331
[lat] => 62.0339
)
[weather] => Array
(
[0] => stdClass Object
(
[id] => 741
[main] => Fog
[description] => fog
[icon] => 50n
)
)
[base] => stations
[main] => stdClass Object
(
[temp] => -47.8
[feels_like] => -47.8
[temp_min] => -48.02
[temp_max] => -47.8
[pressure] => 1028
[humidity] => 63
)
[visibility] => 350
[wind] => stdClass Object
(
[speed] => 1
[deg] => 340
)
[clouds] => stdClass Object
(
[all] => 100
)
[dt] => 1675894338
[sys] => stdClass Object
(
[type] => 2
[id] => 48941
[country] => RU
[sunrise] => 1675898825
[sunset] => 1675928612
)
[timezone] => 32400
[id] => 2013159
[name] => Yakutsk
[cod] => 200
)
Créer sa propre API de météo simplifiée en JSON¶
On peut créer maintenant notre propre mini-API simplifiée en redirigeant la requête vers OpenWeather, puis en simplifiant la réponse fournie :
<?php
header("Content-Type: application/json; charset=utf-8");
if (!empty($_REQUEST['q'])){
$q = $_REQUEST['q'];
require_once('api-key.php');
$apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=" . $q . "&lang=fr&units=metric&APPID=" . API_KEY;
$response = file_get_contents($apiUrl, False);
$data = json_decode($response, true); // $data = TABLEAU PHP
setLocale(LC_TIME,"fr_FR.UTF-8");
date_default_timezone_set("Europe/Paris");
$today = strftime('%A %d %B %y',time());
$hour = date('H:i:s');
// on prépare un tableau $json pour la réponse
$json = array("lieu" => $q,
"jour" => $today,
"heure"=> $hour,
"meteo"=> array());
$json['meteo']['main'] = $data['main'];
$json['meteo']['description'] = $data['weather'][0]['description'];
$json['meteo']['id'] = $data['weather'][0]['id'];
echo json_encode($json,JSON_PRETTY_PRINT);
}
Exécution :¶
Resultat brut html :¶
PHP Deprecated: Function strftime() is deprecated in /Users/roza/work/iut/prog/PHP/php-depot/source/exemples/json/monServiceMeteo.php on line 13
<br />
<b>Deprecated</b>: Function strftime() is deprecated in <b>/Users/roza/work/iut/prog/PHP/php-depot/source/exemples/json/monServiceMeteo.php</b> on line <b>13</b><br />
{
"lieu": "Orleans,fr",
"jour": "Mercredi 08 f\u00e9vrier 23",
"heure": "23:15:22",
"meteo": {
"main": {
"temp": -1.49,
"feels_like": -3.52,
"temp_min": -2.98,
"temp_max": -0.65,
"pressure": 1030,
"humidity": 82
},
"description": "ciel d\u00e9gag\u00e9",
"id": 800
}
}