Adding Query string params to a Guzzle GET request?
To add query string parameters to a GET request using Guzzle, you can use the query option when creating the request.
To add query string parameters to a GET request using Guzzle, you can use the query option when creating the request. The query array automatically handles URL encoding. For example:
Example of adding query string parameters to a GET request using Guzzle
<?php
$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com', [
'query' => [
'param1' => 'value1',
'param2' => 'value2',
],
]);
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
This will send a GET request to "http://example.com?param1=value1¶m2=value2".
You can also modify an existing request object using PSR-7 URI methods. For example:
Example of modifying query parameters on a request object in Guzzle
<?php
$client = new GuzzleHttp\Client();
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://example.com');
$request = $request->withUri(\GuzzleHttp\Psr7\Uri::withQueryValue($request->getUri(), 'param1', 'value1'));
$request = $request->withUri(\GuzzleHttp\Psr7\Uri::withQueryValue($request->getUri(), 'param2', 'value2'));
$response = $client->send($request);Note: Guzzle v6 and v7 use PSR-7 compliant request objects. The older
$client->createRequest()and$request->query->set()syntax is from Guzzle v5 and is no longer supported.