php xml與陣列轉換問題,封裝方法及字串替換
阿新 • • 發佈:2018-12-16
/** * [將xml轉為array] * @param string $xml xml字串或者xml檔名 * @param bool $isFile 傳入的是否是xml檔名 * @return array 轉換得到的陣列 */ public static function xmlToArray($xml,$isFile=false){ //禁止引用外部xml實體 libxml_disable_entity_loader(true); if($isFile){ if(!file_exists($xml)) return false; $xmlStr = file_get_contents($xml); }else{ $xmlStr = $xml; } $result= json_decode(json_encode(simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } /** * [陣列轉xml字元] * @param array $data 需要轉換的陣列 * @return string $xml **/ function arrayToXml($data){ if(!is_array($data) || count($data) <= 0){ return false; } $xml = "<xml>"; foreach ($data as $key=>$val){ if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; } } $xml.="</xml>"; return $xml; }
// Xml 轉 一維陣列 public static function xmlToData($xml, $true) { return (array)simplexml_load_string($xml); } // Xml 轉 陣列, 不包括根鍵 public static function xmlToArray($xml) { $arr = self::xmlToArrayRooted($xml); $key = array_keys($arr); return $arr[$key[0]]; } // Xml 轉 陣列, 包括根鍵 public static function xmlToArrayRooted($xml) { $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/"; if (preg_match_all($reg, $xml, $matches)) { $count = count($matches[0]); $arr = array(); for ($i = 0; $i < $count; $i++) { $key = $matches[1][$i]; $val = self::xmlToArrayRooted($matches[2][$i]); // 遞迴 if (array_key_exists($key, $arr)) { if (is_array($arr[$key])) { if (!array_key_exists(0, $arr[$key])) { $arr[$key] = array($arr[$key]); } } else { $arr[$key] = array($arr[$key]); } $arr[$key][] = $val; } else { $arr[$key] = $val; } } return $arr; } else { return $xml; } } //字串替換 public static function strToData($str, $rule = '') { if (is_array($rule)) { foreach ($rule as $key => $val) { $str = str_replace($val, '', $str); } } else { $str = str_replace($rule, '', $str); } return $str; }