- function postXML($url, $xmlData){
- $header[] = "Content-type: text/xml"; //定义content-type为xml,注意是数组
- $ch = curl_init ($url);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);//超时设置30s
- $response = curl_exec($ch);
- curl_close($ch);
- return $response;
- }
- function getXML(){
- $postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
- return empty($postStr) ? array() : xml_to_array($postStr);
- }
- function array_to_xml($arr, $dom=0, $item=0, $root='root'){
- if (!$dom){
- $dom = new DOMDocument("1.0");
- }
- if(!$item){
- $item = $dom->createElement($root);
- $dom->appendChild($item);
- }
- foreach ($arr as $key=>$val){
- $itemx = $dom->createElement(is_string($key)?$key:"item");
- $item->appendChild($itemx);
- if (!is_array($val)){
- $text = $dom->createTextNode($val);
- $itemx->appendChild($text);
- }else {
- array_to_xml($val,$dom,$itemx);
- }
- }
- return $dom->saveXML();
- }
- function xml_to_array($xml){
- $array = (array)(simplexml_load_string ($xml));
- foreach ($array as $key => $item){
- $array[$key] = struct_to_array ((array)$item);
- }
- return $array;
- }
- function struct_to_array($item){
- if (!is_string($item)) {
- $item = (array)$item;
- foreach($item as $key => $val){
- $item [$key] = struct_to_array ($val);
- }
- }
- return $item;
- }
- function sub_str($str, $length = 0){
- $str = trim($str);
- $strlength = strlen($str);
- if ($length == 0 || $length >= $strlength){
- return $str; //截取长度等于0或大于等于本字符串的长度,返回字符串本身
- }
- elseif ($length < 0) { //如果截取长度为负数
- $length = $strlength + $length;//那么截取长度就等于字符串长度减去截取长度
- if ($length < 0){
- $length = $strlength;//如果截取长度的绝对值大于字符串本身长度,则截取长度取字符串本身的长度
- }
- }
- if (function_exists('mb_substr')){
- $newstr = mb_substr($str, 0, $length, EC_CHARSET);
- }
- elseif (function_exists('iconv_substr')){
- $newstr = iconv_substr($str, 0, $length, EC_CHARSET);
- }
- else{
- //$newstr = trim_right(substr($str, 0, $length));
- $newstr = substr($str, 0, $length);
- }
- return $newstr;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0806201512807.html
来源: http://www.codesnippet.cn/detail/0806201512807.html