以下是一个简单的PHP接口实例,我们将通过一个简单的API来展示如何接收请求、处理数据并返回结果。

1. 项目结构

```

实例php接口例子,PHP接口实例教程:打造高效API服务  第1张

/api/

/controllers/

ExampleController.php

/models/

ExampleModel.php

/routes/

api.php

/views/

index.php

```

2. ExampleModel.php

```php

class ExampleModel {

public function getData() {

// 模拟从数据库获取数据

return ['name' => '张三', 'age' => 20];

}

}

```

3. ExampleController.php

```php

class ExampleController {

private $model;

public function __construct() {

$this->model = new ExampleModel();

}

public function index() {

$data = $this->model->getData();

return json_encode($data);

}

}

```

4. api.php

```php

require_once '../controllers/ExampleController.php';

$controller = new ExampleController();

$controller->index();

```

5. index.php

```php

require_once 'api.php';

```

6. 使用curl测试API

```bash

curl http://localhost/api/

```

7. 返回结果

```

{

"