• PHP Video Tutorials

PHP - json_encode() Function



The json_encode() function can return the JSON representation of a value.

Syntax

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

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

The json_encode() function can return a JSON encoded string on success or false on failure.

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

Output

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

Example 2

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

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

   echo $json;
?>

Output

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

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

Output

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
php_function_reference.htm
Advertisements