user1038814
user1038814

Reputation: 9657

Send xml to webservices using Curl in PHP but returns error

I have a web service to which I send a xml request (application/x-www-form-urlencoded encoded) and get a response back. These are sent to the URL contained within a query parameter called 'xml'

When I use a simple html form such as the one below, I am returned a result. However, when I use my php code, I am returned an error. Perhaps it is because of this: These are sent to the URL contained within a query parameter called 'xml'? If that's the case, how do I send it in that parameter? I'd be very grateful if someone could point out what I've been doing wrong. Many thanks

<form method="post" name="form1" action="http://webservicesapi.com/login.pl">
  <textarea cols="80" rows="20" name="xml">
      <?xml version="1.0"?><request><auth username="hello" password="world" /><method action="login" /></request>
  </textarea>

<input type="submit" value="submit XML document">
</form>

This doesn't work:

<?php
// open a http channel, transmit data and return received buffer
function xml_post($xml, $url, $port)
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];

$ch = curl_init();    // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1);              // Fail on errors

if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port);          //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
}

$data = curl_exec($ch);

curl_close($ch);

return $data;
}

$xml = '<?xml version="1.0"?><request><auth username="hello" password="world" /><method action="login" /></request>';

$url ='http://webservicesapi.com/login.pl';
$port = 80;
$response = xml_post($xml, $url, $port);    
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<P><?=nl2br(htmlentities($response));?></P>
</body>
</html>
?>

Upvotes: 1

Views: 1639

Answers (1)

Zsolt Szeberenyi
Zsolt Szeberenyi

Reputation: 437

CURLOPT_POSTFIELDS expects either an associative array, or a raw post string. Since you are passing it a string, it treats it as a raw post string. So either of these should work:

$response = xml_post(array('xml' => $xml), $url, $port);  

OR

$response = xml_post('xml='.urlencode($xml), $url, $port);  

Upvotes: 2

Related Questions