Page 1 of 1

Posting XML with CURL

Posted: Fri Jul 17, 2009 9:04 am
by jkwok
Hi,

I'm trying to post xml data using CURL but I keep getting errors returned. Since the XML is for work I'm not allowed to post it in full, but I have been assured that it is correctly formatted.

Here is my code:

Code: Select all

 
<?php
 
$url = "https://myurlexample.com/findproducts";
 
$request_xml = '<?xml version="1.0" encoding="UTF-8"?>
 // Purposely truncated
</request>';
 
$header  = "POST /findproducts HTTP/1.1 \r\n";
$header .= "Content-type: application/xml \r\n";
$header .= "Accept: application/xml \r\n";
$header .= "Cache-Control: no-cache \r\n";
$header .= "Pragma: no-cache \r\n";
$header .= "Connection: keep-alive \r\n";
$header .= "Content-length: ".strlen($request_xml)." \r\n\r\n";
$header .= $request_xml;
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, 'jkwok:run467pGH3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_xml);
 
$reply = curl_exec($ch);
 
if(curl_errno($ch))
    print curl_error($ch);
else
    curl_close($ch);
 
echo "<xmp>$reply</xmp>";
?>
 
I get the following error:

Code: Select all

 
HTTP/1.1 100 Continue
HTTP/1.1 500 Internal Server Error 
Connection: close
Server: Jetty(6.1.12.rc2) 
 
If anyone has any ideas as to why this doesn't work I'd greatly appreciate your help!

Thanks,
J

Re: Posting XML with CURL

Posted: Fri Jul 17, 2009 9:57 am
by jkwok
Just as a followup thought... I was wondering about the following which may be why I'm getting this error:

1. Can XML be passed simply as a string like I've done or should it be UTF encoded?
2. Should I be using DOM or SimpleXML to format the XML instead of just having it all as a string?
3. Can CURLOPT_POSTFIELDS accept a single parameter with no identifier?
ex. Should it be curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml' => $request_xml));

Again, any help would be greatly appreciated!

Re: Posting XML with CURL

Posted: Fri Jul 17, 2009 1:07 pm
by requinix
1. If you say the XML is UTF-8 (you do) then it should be UTF-8.
2. No difference.
3. Depends on the specification you're following.

But you aren't supposed to formulate your own request through CURLOPT_HTTPHEADER. That should only contain headers that cURL isn't already being told to send. Get rid of the POST and the Content-Length header.