bukowski
bukowski

Reputation: 1943

How to properly send and receive XML using curl?

I've been trying to post XML and get response from the server but with no luck.

Here are the conditions on server side:

The following requirements apply to the HTTP request:

Here is my script:

$url = "http://somedomain.com";
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<Request PartnerID="asasdsadsa" Type="TrackSearch"> <TrackSearch> <Title>love</Title>    <Tags> <MainGenre>Blues</MainGenre> </Tags> <Page Number="1" Size="20"/> </TrackSearch> </Request>';
$header  = "POST HTTP/1.1 \r\n";
$header .= "Content-type: text/xml \r\n";
$header .= "Content-length: ".strlen($xml)." \r\n";
$header .= "Connection: close \r\n\r\n"; 
$header .= $xml;
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$data = curl_exec($ch); 
echo $data;
if(curl_errno($ch))
    print curl_error($ch);
else
    curl_close($ch);

This gives me:

 HTTP Error 400. The request URL is invalid.
 Bad Request - Invalid URL

Upvotes: 6

Views: 46609

Answers (2)

James
James

Reputation: 22227

Does this help?

<?php
$url = "http://stackoverflow.com";
$xml = '<?xml version="1.0" encoding="UTF-8"?><Request PartnerID="asasdsadsa" Type="TrackSearch"> <TrackSearch> <Title>love</Title>    <Tags> <MainGenre>Blues</MainGenre> </Tags> <Page Number="1" Size="20"/> </TrackSearch> </Request>';

$headers = array(
    "Content-type: text/xml",
    "Content-length: " . strlen($xml),
    "Connection: close",
);

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$data = curl_exec($ch); 
echo $data;
if(curl_errno($ch))
    print curl_error($ch);
else
    curl_close($ch);
?>

Upvotes: 21

Michael Mior
Michael Mior

Reputation: 28753

From the documentation.

CURLOPT_CUSTOMREQUEST

A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

The parameter for CURLOPT_CUSTOMREQUEST should be simply POST and you can use CURLOPT_HTTPHEADER to set headers.

Upvotes: 0

Related Questions