【问题标题】:Getting page with fsockopen使用 fsockopen 获取页面
【发布时间】:2014-05-14 02:14:33
【问题描述】:

我正在尝试访问http://www.example.com:4380/apid/request?method=getXMLTable&name=1&ui=UI&id=12345。它应该以 XML 形式返回输出。 这是代码:

<?

$host = "www.example.com";
$path = "/apid/request?method=getXMLTable&name=1&ui=UI&id=12345";
$port = 4380;

$fp = fsockopen($host, $port, $errno, $errstr, 30);
$buffer ="";
if (!$fp) {
      echo "ERR!!<br>";
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET ".$path." HTTP/1.1\r\n";
        $out .= "Host: ".$host."\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
    
        while (!feof($fp)) {
            $buffer .= fgets($fp, 1024);
        }
        fclose($fp);
}                                                            
 ?>

无论如何我得到的不是 XML 输出,而是这个响应:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Last-Modified: Wed, 02 Apr 2014 16:16:43 GMT
Cache-Control: no-store
Cache-Control: no-cache
Cache-Control: must-revalidate
Cache-Control: pre-check=0
Cache-Control: post-check=0
Cache-Control: max-age=0
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/xml
Transfer-Encoding: chunked
Vary: Accept-Encoding
Date: Wed, 02 Apr 2014 16:16:43 GMT
Connection: close 2000 0

我可以使用提供的代码毫无问题地访问像'www.example.com/path/to/file' 这样的页面。我想我对端口(不是标准的 http )或请求有任何错误。每一条线索都会非常受欢迎。

编辑:

can't 使用任何http 模块!在这种情况下,套接字是必须的! 我已经尝试使用下面的代码,但我在 $body 中什么也没有:

list($header, $body) = explode("\n\n", $buffer, 2);
echo http_chunked_decode($body);

【问题讨论】:

  • 当您使用fsockopen 时,您会在页面内容之前获得所有 HTTP 响应标头。为什么不用file_get_contents

标签: php sockets fsockopen phpwebsocket


【解决方案1】:

您将收到Transfer-Encoding: chunked 回复。您需要使用http_chunked_decode对其进行解码(如果您没有pecl_http,您可以找到PHP version here)。

list($header, $body) = explode("\n\n", $buffer, 2);
echo http_chunked_decode($body);

但正如其他评论者所说,如果您启用了allow_url_fopen,您应该使用file_get_contents,否则使用curl。他们为您处理分块编码。

【讨论】:

  • 它在 $body 中给了我 NULL。如您所见,只有 $buffer 中有标头,因此拆分不起作用...顺便说一句,它应该是 $body,而不是 body。我无法编辑,因为更正太短了
  • 好的,我不确定您是否只是发布了输出的开头。当你直接访问 URL 时,你得到正确的输出,比如 curl?
  • 是的,我在直接访问 URL 时得到输出。
  • 尝试模仿curl 使用的标头。例如,脚本可能需要 User-Agent
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多