Search code examples
phprubyweb-serviceshttpresponsehttpsession

Make a web service call in php


So i have this working in ruby and i want to be able to do this in php. I am using the wamp server if that matters.

Here's the ruby method:

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

I tried looking up other questions and this is where that got me:

$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";
}

Solution

  • http_post_data depends on pecl_http. Unless you must use http_post_data, cURL is probably installed by default on your WAMP server.

    The code below is just an example; I haven't tested it but you get the idea:

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