卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79292本站已运行4413

PHP 函数如何使用 REST API 调用外部函数?

php 函数可以通过 rest api 调用外部函数,具体方法包括使用 curl 或 guzzlehttp 发送 http 请求。curl 可通过 curl_init() 初始化会话,设置请求参数和执行请求;guzzlehttp 则可以通过 request() 方法发送请求。还可以通过代码示例了解使用 curl 和 guzzlehttp 调用外部 api 计算数字总和的实战案例。

PHP 函数如何使用 REST API 调用外部函数?

PHP 函数如何使用 REST API 调用外部函数

简介

REST (Representational State Transfer) API 允许客户端与服务器进行交互,以创建、读取、更新和删除 (CRUD) 数据。PHP 提供了多种方法来使用 REST API,本文将重点介绍如何使用 PHP 函数调用外部函数。

使用 cURL

立即学习“PHP免费学习笔记(深入)”;

cURL 是一个流行的 PHP 库,用于发送 HTTP 请求。以下是如何使用 cURL 调用外部函数:

<?php

$url = 'https://example.com/api/v1/function';
$data = array('name' => 'John', 'age' => 30);
$json_data = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;

?>

使用 GuzzleHTTP

GuzzleHTTP 是另一个 PHP 库,用于发送 HTTP 请求。以下是如何使用 GuzzleHTTP 调用外部函数:

<?php

use GuzzleHttpClient;

$client = new Client();
$response = $client->request('POST', 'https://example.com/api/v1/function', [
    'form_params' => array('name' => 'John', 'age' => 30),
]);

$body = $response->getBody()->getContents();

echo $body;

?>

实战案例

假设我们有一个 API 端点,用于计算两个数字的总和。以下是如何使用 PHP 函数调用此端点:

<?php

// 使用 cURL
$url = 'https://example.com/api/v1/sum';
$data = array('num1' => 10, 'num2' => 20);
$json_data = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

echo $result["sum"]; // 输出:30

// 使用 GuzzleHTTP
$client = new Client();
$response = $client->request('POST', 'https://example.com/api/v1/sum', [
    'form_params' => array('num1' => 10, 'num2' => 20),
]);

$sum = json_decode((string) $response->getBody(), true)["sum"];

echo $sum; // 输出:30

?>
卓越飞翔博客
上一篇: PHP中如何使用异常处理进行单元测试
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏