将php的curl代码转换成curl命令

在开发时,如果有调用第三方接口,在调试时,第三方有没有经常要你把curl命令给他,供他调试,这时又得想办法去封装curl命令。

我给你提供个方法,直接调用即可

/**
     * 将 PHP cURL 请求代码转换为 cURL 命令
     * @param string $method 请求方法,可选值为 "GET" 或 "POST"
     * @param string $url 请求的 URL
     * @param mixed $data 请求数据
     * @param array $headers 请求头
     * @return string 转换后的 cURL 命令
     */
    function convertToCurlCommand($method, $url, $data = null, $headers = array()) {
        $command = 'curl -X ' . $method;

        // 添加 URL
        $command .= ' \'' . $url . '\'';

        // 添加请求头
        foreach ($headers as $header) {
            $command .= ' -H \'' . $header . '\'';
        }

        // 添加请求数据
        if (!empty($data)) {
            if ($method === 'POST') {
                // 根据 Content-Type 头部选择适当的处理方式
                $contentType = '';
                foreach ($headers as $header) {
                    if (strpos($header, 'Content-Type') !== false) {
                        $contentType = $header;
                        break;
                    }
                }

                if (strpos($contentType, 'application/json') !== false) {
                    // Content-Type 为 application/json,将请求数据转换为 JSON 格式
                    $postData = json_encode($data);
                    $command .= ' -d \'' . $postData . '\'';
                } else {
                    // 其他类型的 Content-Type,将数组转换为查询字符串
                    $postData = http_build_query($data);
                    $command .= ' --data \'' . $postData . '\'';
                }
            } else {
                // GET 请求时将数据作为查询字符串拼接到 URL
                $query = http_build_query($data);
                $command .= ' \'' . $url . '?' . $query . '\'';
            }
        }

        return $command;
    }



// 示例代码
$method = 'POST';
$url = 'https://example.com/api';
$data = array(
    'name' => 'John',
    'email' => 'john@example.com'
);
$headers = array(
    'Content-Type: text/html; charset=utf-8',
    'Authorization: Bearer token123'
);

$curlCommand = convertToCurlCommand($method, $url, $data, $headers);
echo $curlCommand;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值