In PHP, the interface that returns an array can be implemented through the following steps:
$response = array( 'status' => 200, 'message' => '请求成功', 'data' => array( 'username' => 'tom', 'age' => 25, 'email' => 'tom@example.com' ) );
json_encode()
function to convert the array into a JSON format string. $json = json_encode($response);
header('Content-Type: application/json');
echo $json;
The complete code is as follows:
$response = array( 'status' => 200, 'message' => '请求成功', 'data' => array( 'username' => 'tom', 'age' => 25, 'email' => 'tom@example.com' ) ); $json = json_encode($response); header('Content-Type: application/json'); echo $json;
When the client requests this interface, it will receive a JSON format string containing the above data. Clients can use methods to parse JSON data into objects or arrays in order to use the data therein.
The above is the detailed content of How to write an array returned by the php interface. For more information, please follow other related articles on the PHP Chinese website!