In PHP, you can use the json_encode() function to convert data into json format. This function can JSON encode PHP variables and return JSON format data. The syntax is "json_encode($value[,$options]) ”; if the conversion fails, FALSE will be returned.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In php, you can use the json_encode() function Convert data to json format.
The json_encode() function can JSON encode PHP variables and return JSON format data; if the conversion fails, FALSE will be returned.
This function accepts one required parameter and one optional parameter:
json_encode ( $value [, $options = 0 ] )
Parameters
value: The value to be encoded. This function is only valid for UTF-8 encoded data.
options: Binary mask consisting of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
Example 1: Convert array to json format
1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); var_dump(json_encode($arr)); ?>
Example 2: Convert array to json format Convert PHP object to JSON format data
name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e); ?>
Example 3: Usage of options parameter in json_encode() function
',"'bar'",'"baz"','&blong&', "\xc3\xa9"); echo "Normal: ", json_encode($a), "
"; echo "Tags: ", json_encode($a, JSON_HEX_TAG), "
"; echo "Apos: ", json_encode($a, JSON_HEX_APOS), "
"; echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "
"; echo "Amp: ", json_encode($a, JSON_HEX_AMP), "
"; echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "
"; echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "
"; $b = array(); echo "Empty array output as array: ", json_encode($b), "
"; echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "
"; $c = array(array(1,2,3)); echo "Non-associative array output as array: ", json_encode($c), "
"; echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "
"; $d = array('foo' => 'bar', 'baz' => 'long'); echo "Associative array always output as object: ", json_encode($d), "
"; echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "
"; ?>
PHP Video Tutorial"
The above is the detailed content of How to convert data into json format in php. For more information, please follow other related articles on the PHP Chinese website!