Search code examples
jsoncurlguzzleopencpu

How to send -d flag from curl with Guzzle


I have the following cURL statement

curl http://localhost/ocpu/library/stats/R/t.test -d "x=x0e48e4cb3f&y=x09aaf63ea6"

When I run this in the terminal everything is fine and I get the response I want, a completed calculation.

Now I'm trying to build this into a PHP application with the use of Guzzle. I have the following code.

$result = $this->client->request('POST', 'http://localhost/ocpu/library/stats/R/t.test', ['json'   => ["x" => $x, "y" => $y],
                                 'header' => ["content" => "application/x-www-form-urlencoded"]])->getBody();

$x and $y contain strings with the values of x and y in the cURL statement.

This gives me the error "400 Bad Request response: not enough 'x' observations"

Using the OpenCPU API Explorer I've figured out that I get the same error when trying to add the x and y parameters as primitive strings by adding quotes around them.

So my problem seems to be that Guzzle sends the x and y parameters as strings instead of Temp keys.

How can I get it to send the exact cURL paramater?

Thank you all in advance.


Solution

  • $params = [
        'x' => 'value',
        'y' => 'value',
    ];
    
    $response = $client->post($uri, [
        'form_params' => $params,
    ]);
    

    I believe the issue is within the code sample that you have supplied. You are using 'json' when 'form_params' is (what i interpret) you are looking for. When 'form_params' is used, content-type headers are automatically set for form data.

    More information can be found within Guzzle 6 Request Options