Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get http headers from Guzzle Response Message as string

Tags:

http

php

guzzle

After doing an http Request by using Guzzle, I want to print all the response headers. How can I do that?

In the guzzle documentation it is stated that the getHeaders() method should be able to cast headers to string, but doing

<?php

    print $response->getHeaders();

?>

does not work. It is also stated that in GuzzleHttp\Message\Response there should be a method called getRawHeaders() that should return the headers as a string, but php tells me that the method is undefined on the Response object. So, how can I accomplish my task of printing all the response headers as a string?

like image 645
user3075898 Avatar asked May 27 '15 16:05

user3075898


People also ask

How do I get data from guzzle response?

As described earlier, you can get the body of a response using the getBody() method. Guzzle uses the json_decode() method of PHP and uses arrays rather than stdClass objects for objects. You can use the xml() method when working with XML data.

How do you send a header on guzzle?

// Set various headers on a request $client->request('GET', '/get', [ 'headers' => [ 'User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'] ] ]); Headers may be added as default options when creating a client.

Can Javascript read HTTP headers?

While you can't ready any headers of HTML response in JS, you can read Server-Timing header, and you can pass arbitrary key-value data through it.

How do I send HTTP request using guzzle?

Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);


2 Answers

If you would like to see a verbose version of response and request headers with Guzzle 6.0, you need to enable the debug option in your request. For example:

$YourGuzzleclient=new Client();
$YourGuzzleclient->request('POST', '{Your url}',
  ['debug'=>true,'otheroptions'=>array()]
);

This option will print all the response and request headers. Check the documentation page where you can find more information.

like image 135
vahob Avatar answered Oct 03 '22 03:10

vahob


I believe you will have to iterate through the headers, try this:

foreach ($response->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "\r\n";
}

As per the api (http://api.guzzlephp.org/class-Guzzle.Http.Message.Response.html#_getRawHeaders), you could do:

echo $response->getRawHeaders();
like image 29
taxicala Avatar answered Oct 03 '22 01:10

taxicala