如何获得HTTP请求作为一个字符串从PHP HTTP流


How to get the HTTP request as a string from PHP HTTP Stream

我使用PHP流与fopen()进行HTTP调用。我想打印HTTP请求作为一个字符串(头和内容),然后通过fopen()发送。

是否有一个函数处理流上下文变量来做到这一点?如果是这样的话,有没有人能发一个简短的例子呢?

下面是一个函数,它需要一个URL,获取它并返回内容:
function do_post_request ($url, $content, $cookie = null) {
  $headers = array("Content-type: application/x-www-form-urlencoded",
                   $cookie);
  $all_headers = implode("'r'n", $headers)."'r'n";
  $params = array('http' => array("method" => "POST",
                                  "content" => $content,
                                  "header" => $all_headers,
                                 ),
                 );
  $ctx = stream_context_create($params);
  $fp = fopen($url, 'rb', false, $ctx);
  if (empty($fp)) {
    throw new Exception("$url: Failed");
  }
  $resp = stream_get_contents($fp);
  if (empty($resp)) {
    throw new Exception("error: bad fetch");
  }
  return $resp
}

我会使用PEAR的HTTP_Request2,它支持拦截和记录发送的标头。