GuzzleHttp客户端 - 发布随机表单数据

时间:2017-01-30 14:59:28

标签: php httpclient guzzle guzzlehttp

让我们以示例开始。

如果我有固定的表格参数(姓名,电子邮件,电话),那么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示例第一次我提交表单时,我有姓名,电子邮件,电话字段。下一次可能是字段名称,电子邮件,电话,father_name,mother_name,兴趣等。。下次可能是姓名,电子邮件,父亲姓名

那么如何使用这种动态表单字段的情况呢?

1 个答案:

答案 0 :(得分:1)

试试这个:

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)
    ]);
}