JSON & PHP

Ajouter un commentaire

Json (JavaScript Object Notation) est un  format d’échange de données en JavaScript. Aucune extension n’est obligatoire pour manipuler du JSON en PHP.

Parmi les fonctions internes au langage PHP :

json_encode :  cette fonction permet d’obtenir la représentation en chaîne de caractères JSON d’une variable PHP.

<?php 
$array = ['x' => 10, 'y' => 20];
$json = json_encode($array);
var_dump($json); // "{"x":10,"y":20}"
?>

Le paramètre en entrée peut être tout type de variable PHP

json_decode : cette fonction permet de décoder une chaîne de caractères JSON afin de récupérer une variable PHP.

<?php
$json = '{"x", 10, "y", 20}';
var_dump($json);
/*
object(stdClass)#1 (2) {
 ["x"] => int(10)
 ["y"] => int(20)
}
*/
var_dump($json, true);
/*
array(2) {
 ["x"] => int(10)
 ["y"] => int(20)
}
*/
/*
Dans cet exemple, le fait de passer la valeur true 
en second paramètre permet de récupérer un tableau associatif 
au lieu d'un objet stdClass
*/

Vous pouvez voir aussi les deux fonctions :

json_last_error()

json_last_error_msg()

Depuis PHP 5.4, l’interface JsonSerializable existe, elle définit une méthode jsonSerializable qui permet de détérminer  comment un objet va réagir à la fonction json_encode

<?php
JsonSerializable {
/* Méthodes */
abstract public mixed jsonSerialize ( void )
}
?>

Voici un exemple d’utilisation :

<?php
class Test implements JsonSerializable {
private $nom;
private $prenom;

public function __construct($val1, $val2){
   $this->nom = $val1;
   $this->prenom = $val2;
}
public function jsonSerialize(){
 return 'json_encode_custom';
}

}

// test
$test = new Test('Toldo', 'Buffon');
$json = json_encode($test);
var_dump($json);
// json_encode_custom
/*
Dans cet exemple la méthode jsonSerialize est implémentée et retourne un message 
customisé
*/
$object = new stdClass();
$object->prop1 = 'valeur1';
$json = json_encode($object);
var_dump($json);
// string(19) "{"prop1":"valeur1"}" 
 ?>