Home Backend Development PHP Problem How to write an array returned by the php interface

How to write an array returned by the php interface

Apr 23, 2023 am 10:09 AM

In PHP, the interface that returns an array can be implemented through the following steps:

  1. Define an array and fill it with data.
$response = array(
    'status' => 200,
    'message' => '请求成功',
    'data' => array(
        'username' => 'tom',
        'age' => 25,
        'email' => 'tom@example.com'
    )
);
Copy after login
  1. Use the json_encode() function to convert the array into a JSON format string.
$json = json_encode($response);
Copy after login
  1. Set the response header to let the client know that JSON data is returned.
header('Content-Type: application/json');
Copy after login
  1. Output JSON data.
echo $json;
Copy after login

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;
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24