PHP curl issue - Trying to send XML post request
I am attempting to make an xml post request which expects a response using curl to build the headers and content. Here is m开发者_如何学Pythony code:
<?php
function post_xml($url, $xml) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/xml; charset=utf-8"));
curl_setopt($ch, CURLOPT_USERPWD, 'myusername:mypassword');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $result;
}
$xml = '<?xml version="1.0" encoding="UTF-8"?><testing><test type="integer">1</test></testing>';
$url = "http://example.com/api/test.php";
$result = post_xml($url, $xml);
echo "<pre>"; print_r($result); echo "</pre>";
?>
To view my outgoing request I use:
$info = curl_getinfo($ch);
echo($info['request_header']);
The resulting HTTP request that is sent is:
POST /api/test.php HTTP/1.1
Authorization: Basic pwmtJdCVwNEawdaODH
Host: example.com
Accept: */*
Content-Type: application/xml; charset=utf-8
Content-Length: 95
The content-length is 95, but then it shows none of the xml content below. This results in a 422 Unprocessable Entity error. Am I completely missing something? I expected to be able to see the XML in the request sent.
You haven't specified a fieldname for your XML content, so PHP has nowhere to assign it in the POST request. As the manual states:
This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value.
So try:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml' => $xml));
Don't know if this is what your API is expecting, but it's one thing to look into.
As for displaying the XML, remember that browsers can/will interpret it as HTML, and any unknown tags will simply not be displayed. Try doing your output as:
echo "<pre>";
echo htmlspecialchars($result);
echo "</pre>";
and/or outputting header('Content-type: text/plain')
so that the XML tags will be displayed as-is and not be interpreted as unknown html tags.
echo($info['request_header']);
will only show the header that was sent. It will not show the post data, so you should not see the XML string.
It works when I removed the header line:
//curl_setopt($ch, CURLOPT_HTTPHEADER, ...
Final code:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $xml));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
精彩评论