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
輸出。