简体   繁体   中英

PHP, How do I get clean XML POST content into a variable?

I have written a PHP script that posts XML to my server:

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

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

I'm trying to figure out how to parse that request on the server side. If I do this:

print_r($_POST);

It returns:

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

I want to be able to pass the post into one of the XML parsers. For example simplexml_load_string() . I need access to the clean XML file. How do I access the POST request so I get a clean file?

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'].

php://input allows you to read raw POST data in PHP.

For Example:

On the client side:

<?php
$ch = curl_init();
$file = file_get_contents("stuff.xml");
$url = "http://traalala.com/foobar";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$file);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>

In the Controller on the Server side:

$post = file_get_contents("php://input");
print $post;

Firing off the post, the controller grabs the post data.

You get clean XML output printed to screen as defined in the stuff.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM