forked from shuber/curl
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathResponse.php
78 lines (69 loc) · 2.15 KB
/
Response.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace maxwen\yii\curl;
/**
* Parses the response from a Curl request into an object containing
* the response body and an associative array of headers
*
* @package curl
* @author Sean Huber <[email protected]>
**/
class Response {
/**
* The body of the response without the headers block
*
* @var string
**/
public $body = '';
/**
* An associative array containing the response's headers
*
* @var array
**/
public $headers = array();
/**
* Accepts the result of a curl request as a string
*
* <code>
* $response = new CurlResponse(curl_exec($curl_handle));
* echo $response->body;
* echo $response->headers['Status'];
* </code>
*
* @param string $response
**/
function __construct($response) {
# Headers regex
$pattern = '#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims';
# Extract headers from response
preg_match_all($pattern, $response, $matches);
$headers_string = array_pop($matches[0]);
$headers = explode("\r\n", str_replace("\r\n\r\n", '', $headers_string));
# Remove headers from the response body
$this->body = str_replace($headers_string, '', $response);
# Extract the version and status from the first header
$version_and_status = array_shift($headers);
preg_match('#HTTP/(\d\.\d)\s(\d\d\d)\s(.*)#', $version_and_status, $matches);
$this->headers['Http-Version'] = $matches[1];
$this->headers['Status-Code'] = $matches[2];
$this->headers['Status'] = $matches[2].' '.$matches[3];
# Convert headers into an associative array
foreach ($headers as $header) {
preg_match('#(.*?)\:\s(.*)#', $header, $matches);
$this->headers[$matches[1]] = $matches[2];
}
}
/**
* Returns the response body
*
* <code>
* $curl = new Curl;
* $response = $curl->get('google.com');
* echo $response; # => echo $response->body;
* </code>
*
* @return string
**/
function __toString() {
return $this->body;
}
}