tags:

views:

180

answers:

1

I have written a script that posts an XML request to my server. See below:

$xml_request='<?xml version="1.0"?><request><data></data></request>';
$url='http://www.myserver.com/xml_request.php';

//Initialize handle and set options

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 4); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_request); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));

$result = curl_exec($ch); 

curl_close($ch);

Now I'm trying to figure out how to parse that request on the server side. If I do a simple

print_r($_POST);

it returns:

Array
(
    [<?xml_version] => \"1.0\"?><request><data></data></request>
)

which doesn't seem right. I want to be able to pass the post into one of the XML parsers - most likely simplexml_load_string(), so I need access to the clean XML file. How do I access the POST request so I get a clean file?

+2  A: 

The problem is with the script that posts the request. You need to encode the XML string before you send it to the server in order to prevent the server from parsing it. Try running your XML through rawurlencode before you post it to the server.


Looking into this more, I saw another problem. It looks like the CURLOPT_POSTFIELDS option expects you to form the string yourself. Quoth the manual page (bold is mine):

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

So in your case, it would be something like

curl_setopt($ch, CURLOPT_POSTFIELDS, 'xmlstring='.rawurlencode($xml_request))

And then in your receiving script, you'd expect to be able to access it as $_POST['xmlstring'].

notJim
I tried what you suggested. Assigning xmlstring to the xml content worked, but adding the url encoding seems to break it. No error is thrown, but the POST variable array shows empty when I encode it. I even tried decoding it on the other end. At least it works now. I've written a number of XML requests in the past where you don't specify a variable name for the XML string. UPS's XML system and Authorize.net don't have variable names passed. I'm not sure how they read it in on the other end, but would like to know. Can you access it via $_POST[0] or something along those lines?
In my example in the answer, you'd be able to access it as $_POST['xmlstring']. I just tried running your code, but with the one curl_setopt line set as in my answer above, and was able to get the expected xml string. I had a typo in my answer before, so if you copied and pasted, that might be your problem (it was missing the $ch in curl_setopt).
notJim