json_encode() 函数是一个用于将 PHP 数据结构转换为 JSON 格式的函数。
使用方法如下:
json_encode( $variable, $options, $depth );
其中,
示例代码:
$data = array(
'name' => 'John',
'age' => 30,
'hobbies' => array('reading', 'music', 'travel'),
'address' => array(
'street' => '123 Main St',
'city' => 'New York',
'state' => 'NY'
)
);
$json = json_encode($data);
echo $json;
输出结果:
{"name":"John","age":30,"hobbies":["reading","music","travel"],"address":{"street":"123 Main St","city":"New York","state":"NY"}}
以上代码将 PHP 数组转换为 JSON 字符串,并通过 echo
输出。