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
<?php header('content-type:text/html;charset=utf-8'); $arr = array ('a'=>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
<?php header('content-type:text/html;charset=utf-8'); class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->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
<?php header('content-type:text/html;charset=utf-8'); $a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9"); echo "Normal: ", json_encode($a), "<br>"; echo "Tags: ", json_encode($a, JSON_HEX_TAG), "<br>"; echo "Apos: ", json_encode($a, JSON_HEX_APOS), "<br>"; echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "<br>"; echo "Amp: ", json_encode($a, JSON_HEX_AMP), "<br>"; echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "<br>"; echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "<br><br>"; $b = array(); echo "Empty array output as array: ", json_encode($b), "<br>"; echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "<br><br>"; $c = array(array(1,2,3)); echo "Non-associative array output as array: ", json_encode($c), "<br>"; echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "<br><br>"; $d = array('foo' => 'bar', 'baz' => 'long'); echo "Associative array always output as object: ", json_encode($d), "<br>"; echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "<br><br>"; ?>
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!