首页 > 解决方案 > 将 CURL 命令转换为 PHP Curl

问题描述

我有以下命令可以在 PHP 中运行,它按预期工作:

$params = [
        'file' => $xmlLocalPath,
        'type' => 'mismo',
        'file_type' => $xmlFile['file_type'],
        'filename' => $xmlFile['file_name']
    ];

$cmd =
        'curl -X POST ' . $this->outboundBaseURL . 'document \
        -H "Accept: application/json" \
        -H "Authorization: Bearer ' . $this->token . '" \
        -H "Cache-Control: no-cache" \
        -H "Content-Type: multipart/form-data" \
        -F "file=@' . $params['file'] . ';type=' . $params['file_type'] . '" \
        -F "type=' . $params['type'] . '" \
        -F "filename=' . $params['filename'] . '"';
    exec($cmd, $result);

我需要使用 PHP 的 curl 库让它工作,但我不能让它工作得很好。我在 PHP 5.6 上,这就是我现在所拥有的:

$params = [
        'file' => $xmlLocalPath,
        'type' => 'mismo',
        'file_type' => $xmlFile['file_type'],
        'filename' => $xmlFile['file_name']
    ];

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $this->outboundBaseURL . 'document',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_HTTPHEADER => [
            'Accept: application/json',
            'Authorization: Bearer ' . $this->token,
            'Cache-Control: no-cache',
            'Content-Type: multipart/form-data'
        ]
    ]);

    curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking

    $response = curl_exec($ch);
    $err = curl_error($ch);

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

我知道问题必须与 POSTFIELDS,尤其是文件有关,但我没有展示如何以适当的方式为 PHP CURL 提供参数,以便文件和其他参数将像在原始 curl 中一样发送称呼。我知道“@”方法在 PHP Curl 中已被弃用,我也尝试将 curl_file_create 与本地文件一起使用,但没有成功

标签: phpcurl

解决方案


尝试再添加一个参数:

CURLOPT_POST => 1

推荐阅读