替代fsockopen与卷曲在PHP中

时间:2014-09-30 17:09:33

标签: php web-services sockets curl

我正在尝试在我的php代码中调用运输公司的Web服务并获取结果xml。我有这个示例代码,我想知道是否有使用curl的替代方法。

代码:

  function doPost($_postContent) {
    $postContent = "xml_in=".$_postContent;

    $host="test.company.com";
    $contentLen = strlen($postContent);

    $httpHeader ="POST /shippergate2.asp HTTP/1.1\r\n"
        ."Host: $host\r\n"
        ."User-Agent: PHP Script\r\n"
        ."Content-Type: application/x-www-form-urlencoded\r\n"
        ."Content-Length: $contentLen\r\n"
        ."Connection: close\r\n"
        ."\r\n";

    $httpHeader.=$postContent;


        $fp = fsockopen($host, 81);

        fputs($fp, $httpHeader);

        $result = "";

        while(!feof($fp)) {
                // receive the results of the request
                $result .= fgets($fp, 128);
        }

        // close the socket connection:

        fclose($fp);

        $result = explode("\r\n\r\n", $result,3);
}

我可以使用curl调用它吗?

2 个答案:

答案 0 :(得分:1)

您可以使用CURLOPT_PORT选项将端口更改为81.请参阅http://php.net/manual/en/function.curl-setopt.php

$url = "http://test.company.com/shippergate2.asp";

$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, 81);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "PHP Script");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postContent);
$data = curl_exec($ch);

答案 1 :(得分:0)

我想需要一个完整的解决方案,但我建议检查PHP https://github.com/shuber/curl的基本CURL包装器