实际开发中经常遇到的问题,这里整理了发送和接收代码示例,遇到时可以参考。
发送json:
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
接收json:
$json_input_data=json_decode(file_get_contents('php://input'),TRUE);
print_r( $json_input_data);
发送XML:
function sendRequest($requestXML)
{
$server = 'http://www.something.com/myapp';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
curl_close($ch);
}
return $data;
}
接收xml:
$dataPOST = trim(file_get_contents('php://input'));
$xmlData = simplexml_load_string($dataPOST);