在 php 中进行 Web 服务调用


Make a web service call in php

所以我在 ruby 中工作,我希望能够在 php 中做到这一点。如果这很重要,我正在使用 wamp 服务器。

这是 ruby 方法:

def response(url, body)
 uri = URI(url)
 request = Net::HTTP::Post.new(uri.request_uri)
 request.body = body
 http_session = Net::HTTP.new(uri.hostname, uri.port)
 http_session.use_ssl = (uri.scheme == "https")
 http_session.verify_mode = OpenSSL::SSL::VERIFY_NONE
 response = http_session.request(request)
 return response.body
end

我尝试查找其他问题,这就是让我感到震惊的地方:

$request_info = array();
$REQUEST_BODY = 'request body';
$full_response = @http_post_data(
    'url',
    $REQUEST_BODY,
    array(
        'headers' => array(
            'Content-Type' => 'text/xml; charset=UTF-8',
            'SOAPAction' => 'HotelAvail',
        ),
        'timeout' => 60,
    ),
    $request_info
);
$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));
foreach ($response_xml->xpath('//@HotelName') as $HotelName) {
    echo strval($HotelName) . "'n";
}

http_post_data取决于pecl_http。 除非必须使用 http_post_data,否则默认情况下可能会在 WAMP 服务器上安装 cURL。

下面的代码只是一个示例;我还没有测试过它,但你明白了:

$headers = array(
    'Content-Type' => 'text/xml; charset=UTF-8',
    'SOAPAction' => 'HotelAvail',
);
$ch = curl_init($server_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$full_response = curl_exec($ch);
curl_close($ch);