/** * 返回結果集 * * @param mixed $info 返回的有效資料集或是錯誤說明 * @param string $msg 為空白或是錯誤類型代號 * @param string $result 請求成功或是失敗的標識 * @param int $post 1為xml方式,2為json方式 * */function getData($info, $msg = '', $post, $result = 'success'){ /* 分為xml和json兩種方式 */ $data_arr = array('result'=>$result, 'msg'=>$msg, 'info'=>$info); $data_arr = to_utf8_iconv($data_arr); //確保傳遞的編碼為UTF-8 if ($post == 1) { /* xml方式 */ if (class_exists('DOMDocument')) { $doc=new DOMDocument('1.0','UTF-8'); $doc->formatOutput=true; $shopex=$doc->createElement('kewin'); $doc->appendChild($shopex); $result=$doc->createElement('result'); $shopex->appendChild($result); $result->appendChild($doc->createCDATASection($data_arr['result'])); $msg=$doc->createElement('msg'); $shopex->appendChild($msg); $msg->appendChild($doc->createCDATASection($data_arr['msg'])); $info=$doc->createElement('info'); $shopex->appendChild($info); create_tree($doc, $info, $data_arr['info']); die($doc->saveXML()); } die('' . array2xml($data_arr)) ; } else { /* json方式 */ $json = new JSON; die($json->encode($data_arr)); //把產生的返回字串列印出來 }}/** * 迴圈產生xml節點 * * @param handle $doc xml執行個體控制代碼 * @param handle $top 當前父節點 * @param array $info_arr 需要解析的數組 * @param boolean $have_item 是否是資料數組,是則需要在每條資料上加item父節點 * */function create_tree($doc, $top, $info_arr, $have_item = false){ if (is_array($info_arr)) { foreach ($info_arr as $key => $val) { if (is_array($val)) { if ($have_item == false) { $data_info=$doc->createElement('data_info'); $top->appendChild($data_info); create_tree($doc, $data_info, $val, true); } else { $item=$doc->createElement('item'); $top->appendChild($item); $key_code = $doc->createAttribute('key'); $item->appendChild($key_code); $key_code->appendChild($doc->createTextNode($key)); create_tree($doc, $item, $val); } } else { $text_code=$doc->createElement($key); $top->appendChild($text_code); if (is_string($val)) { $text_code->appendChild($doc->createCDATASection($val)); } else { $text_code->appendChild($doc->createTextNode($val)); } } } } else { $top->appendChild($doc->createCDATASection($info_arr)); }}function array2xml($data,$root='shopex'){ $xml='<'.$root.'>'; _array2xml($data,$xml); $xml.=''; return $xml;}function _array2xml(&$data,&$xml){ if(is_array($data)){ foreach($data as $k=>$v){ if(is_numeric($k)){ $xml.=''; $xml.=_array2xml($v,$xml); $xml.=''; }else{ $xml.='<'.$k.'>'; $xml.=_array2xml($v,$xml); $xml.=''; } } }elseif(is_numeric($data)){ $xml.=$data; }elseif(is_string($data)){ $xml.=''.$data.''; }}
調用方法getData()傳入不同的參數可分別產生xml資料或json格式資料
getData($data, '', 'json'); //返回json資料
{"result":"success","msg":"","info":{"data_info":[{"goods_id":"1","last_modify":"1423937979"},{"goods_id":"2","last_modify":"1425595831"},{"goods_id":"3","last_modify":"1423937959"},{"goods_id":"4","last_modify":"1423942862"}],"counts":"4"}}
getData($data, '', 'xml'); //返回xml資料
success
1
1423937979
2
1425595831
3
1423937959
4
1423942862
4