PHP - Función json_encode ()

La función json_encode () puede devolver la representación JSON de un valor.

Sintaxis

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

La función json_encode () puede devolver una cadena que contenga la representación JSON del valor proporcionado. La codificación se ve afectada por las opciones proporcionadas y, además, la codificación de los valores flotantes depende del valor de serialize_precision.

La función json_encode () puede devolver una cadena codificada JSON en caso de éxito o falso en caso de error.

Ejemplo 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";
?>

Salida

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

Ejemplo 2

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

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

   echo $json;
?>

Salida

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

Ejemplo 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;
?>

Salida

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