PHP: Create JSON String from Array / Object – json_encode()

Generating Random String Using PHP

json_encode() function is an inbuilt PHP function which is used to convert PHP array or object into JSON representation. Encoding is used to bundle data with respect to a particular format. This process will be required to preserve data consistency. 

Convert array to JSON:

<?php 

$input_ary = array();
$input_ary['array_key_1'] = 'array_value_1';
$input_ary['array_key_2'] = 'array_value_2';
$input_ary['array_key_3'] = 'array_value_3';
$input_ary['array_key_4'] = 'array_value_4';
$input_ary['array_key_5'] = 'array_value_5';

$json_result = json_encode($input_ary);
echo $json_result;

?>

Result:

{"array_key_1":"array_value_1","array_key_2":"array_value_2","array_key_3":"array_value_3",
"array_key_4":"array_value_4","array_key_5":"array_value_5"}  

Convert Object to JSON – new stdClass():

<?php  

$input_object = new stdClass(); 
$input_object->array_key_1 = 'array_value_1';
$input_object->array_key_2 = 'array_value_2';
$input_object->array_key_3 = 'array_value_3';
$input_object->array_key_4 = 'array_value_4';
$input_object->array_key_5 = 'array_value_5';

$json_result = json_encode($input_object);
echo $json_result;

?>

Result:

{"array_key_1":"array_value_1","array_key_2":"array_value_2","array_key_3":"array_value_3",
"array_key_4":"array_value_4","array_key_5":"array_value_5"}  

Convert Object to JSON – (object)array():

<?php 

$input_object = (object)array(); 
$input_object->array_key_1 = 'array_value_1';
$input_object->array_key_2 = 'array_value_2';
$input_object->array_key_3 = 'array_value_3';
$input_object->array_key_4 = 'array_value_4';
$input_object->array_key_5 = 'array_value_5';

$json_result = json_encode($input_object);
echo $json_result;

?>

Result:

{"array_key_1":"array_value_1","array_key_2":"array_value_2","array_key_3":"array_value_3",
"array_key_4":"array_value_4","array_key_5":"array_value_5"}  

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *