MaMu
MaMu

Reputation: 1869

Getting page with fsockopen

I'm trying to access http://www.example.com:4380/apid/request?method=getXMLTable&name=1&ui=UI&id=12345. It should give back output as XML. This is the code:

<?

$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);
}                                                            
 ?>

Anyhow I'm getting not the XML output, but this response:

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

I can access pages like 'www.example.com/path/to/file' with the presented code without any problems. I guess I make any mistake with port(not standard http ) or request. Every clue would be very welcome.

EDIT:

I can't use any http module! Socket is a must in this case! I have tried with the code below, but I get nothing in $body:

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

Upvotes: 1

Views: 1457

Answers (1)

akirk
akirk

Reputation: 6837

You are getting a Transfer-Encoding: chunked response. You need to use http_chunked_decode to decode it (you can find a PHP version here, if you don't have pecl_http).

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

But as the other commenter said, you should really use file_get_contents if you have allow_url_fopen enabled or curl otherwise. They handle the chunked encoding for you.

Upvotes: 2

Related Questions