How to write an example code for developing PHP interfaces?
Here is a simple example code demonstrating how to develop an API using PHP.
<?php
// 配置响应头,允许跨域访问
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// 接收请求参数
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// 处理请求,这里只是简单的将两个参数进行相加
$result = $param1 + $param2;
// 构造响应数据
$response = array(
"result" => $result
);
// 返回响应数据
echo json_encode($response);
?>
The code above utilizes the header function to set the response header, allowing cross-origin access. It then uses $_GET to retrieve request parameters, processes the parameters to construct response data, and uses json_encode to convert the response data to JSON format. Finally, it uses echo to output the response data.
This is just a simple example code, in actual development, more complex handling may be needed depending on specific requirements, such as database operations, calling other interfaces, etc.