【问题标题】:Alternative of fsockopen with curl in php在 php 中使用 curl 替代 fsockopen
【发布时间】:2014-11-25 09:47:39
【问题描述】:

我试图在我的 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 调用它吗?

【问题讨论】:

    标签: php web-services sockets curl


    【解决方案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);
    

    【讨论】:

    • 谢谢回复。 “标准”是什么意思?
    • 抱歉,这可能造成了混淆。标准 HTTP 1.1 是 RFC 2616。您发布的示例是标准 HTTP,这适用于此。
    • 我还需要包含标题吗:内容类型/长度等...?
    • cURL 将处理 Content-TypeContent-LengthHostConnection 标头。您必须手动设置 User-Agent - 我添加了一个示例。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 2011-06-18
      • 2011-06-23
      • 2012-11-01
      • 2010-10-17
      • 1970-01-01
      • 2011-02-26
      • 2011-06-21
      • 2018-07-02
      相关资源
      最近更新 更多