1. 程式人生 > >php陣列與xml的相互轉化

php陣列與xml的相互轉化

**
 * 將陣列轉換成 XML
 *
 * @param array $data             陣列
 * @param array $encoding         編碼(預設是 UTF-8)
 * @param string $rootNodeName    根節點名稱(預設是 data)
 * @param SimpleXMLElement $xml   XML物件(遞迴用)
 * @return string XML
 */
function toXml($data, $encoding = 'UTF-8', $rootNodeName = 'data', $xml = null
) { if ($xml == null) { $xml = simplexml_load_string('<?xml version="1.0" encoding="'.$encoding.'"?><'.$rootNodeName.' />'); } foreach($data as $key => $value) { if (is_numeric($key)) { $key = 'item'; } $key = preg_replace('/\W+/i', ''
, $key); if (is_array($value)) { $node = $xml->addChild($key); toXml($value, $encoding, $rootNodeName, $node); } else { //$value = htmlentities($value); $xml->addChild($key, $value); } } return $xml->asXML(); }
function
xml_to_array($xml){
$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/"; if(preg_match_all($reg, $xml, $matches)){ $count = count($matches[0]); for($i = 0; $i < $count; $i++){ $subxml= $matches[2][$i]; $key = $matches[1][$i]; if(preg_match( $reg, $subxml )){ $arr[$key] = xml_to_array( $subxml ); }else{ $arr[$key] = $subxml; } } } return $arr; }