PHP - Fonction json_encode ()

La fonction json_encode () peut renvoyer la représentation JSON d'une valeur.

Syntaxe

string json_encode( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

La fonction json_encode () peut renvoyer une chaîne contenant la représentation JSON de la valeur fournie. Le codage est affecté par les options fournies et, en outre, le codage des valeurs flottantes dépend de la valeur de serialize_precision.

La fonction json_encode () peut renvoyer une chaîne codée JSON en cas de succès ou false en cas d'échec.

Exemple 1

<?php
   $post_data = array(
      "item" => array(
            "item_type_id" => 1,
            "tring_key" => "AA",
            "string_value" => "Hello",   
            "string_extra" => "App",
            "is_public" => 1,
            "is_public_for_contacts" => 0
      )
   );
   echo json_encode($post_data)."\n";
?>

Production

{"item":{"item_type_id":1,"tring_key":"AA","string_value":"Hello","string_extra":"App","is_public":1,"is_public_for_contacts":0}}

Exemple 2

<?php
   $array = array("Coffee", "Chocolate", "Tea");

   // The JSON string created from the array
   $json = json_encode($array, JSON_PRETTY_PRINT);

   echo $json;
?>

Production

[
    "Coffee",
    "Chocolate",
    "Tea"
]

Exemple 3

<?php
   class Book {
      public $title = "";
      public $author = "";
      public $yearofpublication = "";
   }

   $book = new Book();
   $book->title = "Java";
   $book->author = "James Gosling";
   $book->yearofpublication = "1995";

   $result = json_encode($book);
   echo "The JSON representation is:".$result."\n";

   echo "************************". "\n";
   echo "Decoding the JSON data format into an PHP object:"."\n";
   $decoded = json_decode($result);

   var_dump($decoded);

   echo $decoded->title."\n";
   echo $decoded->author."\n";
   echo $decoded->yearofpublication."\n";

   echo "************************"."\n";
   echo "Decoding the JSON data format into an PHP array:"."\n";
   $json = json_decode($result,true);

   // listing the array
   foreach($json as $prop => $value)
      echo $prop ." : ". $value;
?>

Production

The JSON representation is:{"title":"Java","author":"James Gosling","yearofpublication":"1995"}
************************
Decoding the JSON data format into an PHP object:
object(stdClass)#2 (3) {
  ["title"]=>
  string(4) "Java"
  ["author"]=>
  string(13) "James Gosling"
  ["yearofpublication"]=>
  string(4) "1995"
}
Java
James Gosling
1995
************************
Decoding the JSON data format into an PHP array:
title : Javaauthor : James Goslingyearofpublication : 1995