Friday, January 13

php json encode and decode example

<?php
echo "<br><h1>JSON Encode_decode with php</h1></br>";
echo"JSON_DECODE<br/>--------------------------------------------";
echo"<br/>";
$json = '{"a":1,"b":2,"c":3}';//Example 1
$j=json_decode($json);

echo "Value a= ". $j->{'a'};
echo "Value b= ". $j->{'b'};
echo "Value c= ". $j->{'c'};

echo"<br/>--------------------------------------------";
echo"<br/>";
echo"JSON_ENCODE<br/>--------------------------------------------";
echo"<br/>";

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);//Example 2
echo json_encode($arr);
echo"<br/>";
// Output {"a":1,"b":2,"c":3,"d":4,"e":5}


$arr = array ( 1, 2, 3, 4, 5 ); //Example 3
echo json_encode($arr);
echo"<br/>";
// Output [1,2,3,4,5]


$arr['x'] = 10;  //Example 4
echo json_encode($arr);
echo"<br/>";
// Output {"0":1,"1":2,"2":3,"3":4,"4":5,"x":10}


echo json_encode(54321); //Example 5
echo"<br/>";
// Output 54321
echo"<br/>--------------------------------------------";

//Example 1

echo "<br/>Example #1 : The following example shows how to convert an ARRAY INTO JSON WITH PHP
<br/><br/><br/>";

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
echo "<br/>";

//Example 2


echo "<br/>Example #2 : The following example shows HOW THE PHP OBJECTS CAN BE CONVERTED INTO JSON
<br/><br/><br/>";

class Emp {
public $name = "";
public $hobbies = "";

}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";

echo json_encode($e);

//Example 3

echo "<br/>Example #3 : The following example shows HOW PHP CAN BE USED TO DECODE JSON OBJECTS
<br/><br/><br/>";

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo "<pre>".var_dump(json_decode($json))."</pre>";
echo "<pre>".var_dump(json_decode($json, true))."</pre>";
echo "<br/>";

//Example 4

echo "<br/>Example #3 : The following example shows HOW PHP CAN BE USED TO DECODE JSON OBJECTS
<br/><br/><br/>";

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo "<pre>".var_dump(json_decode($json))."</pre>";
echo "<pre>".var_dump(json_decode($json, true))."</pre>";
echo "<br/>";


?>

No comments:

Post a Comment

10 Best Chatting Apps In India

  The modern world is all about Internet. There was a time when people use to pay high telephone bills to stay in touch with their friends a...