GuzzleHttp 客户端 - post 随机表单数据

GuzzleHttp Client - post random form data

让我们从例子开始。

如果我有固定的表单参数(名称、电子邮件、phone),那么 Guzzle Post 方法代码将是这样的:

public function test(Request $request){
$client = new \GuzzleHttp\Client();

    $url = www.example.com

    $res = $client->post($url.'/article',[
        'headers' => ['Content-Type' => 'multipart/form-data'],
        'body' => json_encode([
            'name' => $request['name'],
            'email' => $request['email'],
            'write_article' => $request['article'],
            'phone' => $request['phone'],
        ])
    ]);
}

以上代码运行良好。

但是当没有固定的表单参数时如何使用 Guzzle 发送数据?

Foe 示例,当我第一次提交表单时,我有 name 、 email 、 phone 字段。下一次可能是字段 name , email , phone , father_name , mother_name, interest 等.. 。下次可能是 姓名,电子邮件,父亲姓名

那么如何处理这种动态表单字段情况?

试试这个:

public function test(Request $request)
{
    $client = new \GuzzleHttp\Client();
    $url = 'www.example.com';

    $body = [];

    // exceptions, for when you want to rename something
    $exceptions = [
        'article' => 'write_article',
    ];

    foreach ($request as $key => $value) {
        if (isset($exceptions[$key])) {
            $body[$exceptions[$key]] = $value;
        } else {
            $body[$key] = $value;
        }
    }

    $res = $client->post($url.'/article',[
        'headers' => ['Content-Type' => 'multipart/form-data'],
        'body' => json_encode($body)
    ]);
}