CodeIgniter 한국사용자포럼 BETA
빠르고, 유연한 PHP Framework!

TIP게시판


array2xml,xml2array 라이브러리.      
양승현 0 1,956 0 0 2010-06-08 10:10:12
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
    include_once("class.array2xml2array.php");

    $admins = array("admin1", "admin2", "admin3");
    $config = array("config" => array(
                            "filepath" => "/tmp",
                            "interval" => 5,
                            "admins"=>$admins));

    $array2XML = new CArray2xml2array();

    // no root
    $array2XML->setArray($admins);
    if ($array2XML->saveArray("admins.xml", "admins")){
        echo "admins array save<br>";
    }

    // one root
    $array2XML->setArray($config);
    if($array2XML->saveArray("config.xml")){
        echo "config array save<br>";
    }
*/
class array2xml {

/*
 * XML Array
 * @var array
 * @access private
 */
private $XMLArray;

/*
 * array is OK
 * @var bool
 * @access private
 */
private $arrayOK;

/*
 * XML file name
 * @var string
 * @access private
 */
private $XMLFile;

/*
 * file is present
 * @var bool
 * @access private
 */
private $fileOK;

/*
 * DOM document instance
 * @var DomDocument
 * @access private
 */
private $doc;

/**
 * Constructor
 * @access public
 */

public function __construct(){

}

/**
 * setteur setXMLFile
 * @access public
 * @param string $XMLFile
 * @return bool
 */

public function setXMLFile($XMLFile){
	if (file_exists($XMLFile)){
		$this->XMLFile = $XMLFile;
		$this->fileOK = true;
	}else{
		$this->fileOK = false;
	}
	return $this->fileOK;
}

/**
 * saveArray
 * @access public
 * @param string $XMLFile
 * @return bool
 */

public function saveArray($XMLFile, $rootName="", $encoding="utf-8", $filepath){
	global $debug;
	$this->doc = new DOMDocument("1.0", $encoding);
	$arr = array();
	
	if (count($this->XMLArray) > 1){
		if ($rootName != ""){
			$root = $this->doc->createElement($rootName);
		}else{
			$root = $this->doc->createElement("root");
			$rootName = "root";
		}
		$arr = $this->XMLArray;
	}else{
		$key = key($this->XMLArray);
		$val = $this->XMLArray[$key];

		if (!is_int($key)){
			$root = $this->doc->createElement($key);
			$rootName = $key;
		}else{
			if ($rootName != ""){
				$root = $this->doc->createElement($rootName);
			}else{
				$root = $this->doc->createElement("root");
				$rootName = "root";
			}
		}
		$arr = $this->XMLArray[$key];
	}

	$root = $this->doc->appendchild($root);
	
	$this->addArray($arr, $root, $rootName, 0);

/*        foreach ($arr as $key => $val){
		$n = $this->doc->createElement($key);
		$nText = $this->doc->createTextNode($val);
		$n->appendChild($nodeText);
		$root->appendChild($n);
	}
*/
	$result = $this->doc->save($filepath.$XMLFile);
	if ($result == 0){
		return false;
	}else{
		return true;
	}
}

/**
 * addArray recursive function
 * @access public
 * @param array $arr
 * @param DomNode &$n
 * @param string $name
 */

function addArray($arr, &$n, $name="", $deps = 0){
	foreach ($arr as $key => $val){
		if (is_int($key)){
			if (strlen($name)>1){
				$newKey = substr($name, 0, strlen($name)-1);
			}else{
				$newKey="item";
			}
		}else{
			$newKey = $key;
		}

		$node = $this->doc->createElement($newKey);
		
		if (is_array($val)){	
			$this->addArray($arr[$key], $node, $key, $deps+1);
		}else{
			$nodeText = $this->doc->createTextNode($val);
			$node->appendChild($nodeText);		
		}	

		$newline = $this->doc->createTextNode("\n");
		$n->insertBefore($newline);
		
		for($i=0; $i <= $deps; $i++){
		$tab = $this->doc->createTextNode("\t");
			$n->insertBefore($tab);
		}
		
		$n->appendChild($node);
	}
}


/**
 * setteur setArray
 * @access public
 * @param array $XMLArray
 * @return bool
 */

public function setArray($XMLArray){
	if (is_array($XMLArray) && count($XMLArray) != 0){
		$this->XMLArray = $XMLArray;

		$this->arrayOK = true;
	}else{
		$this->arrayOK = false;
	}
	return $this->arrayOK;
}

}//End of the class
?>
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * xml2array Class
 *
 * This class converts XML data to array representation.
 *
 * $this->load->library('xml2array');
 * $xml_array = $this->xml2array->parse($xml);
 */
class Xml2array
{
	function parse($xml, $get_attributes = 1, $priority = 'tag')
	{
		$contents = "";
		if (!function_exists('xml_parser_create'))
		{
			return array ();
		}
		$parser = xml_parser_create('');
		if (!($fp = @ fopen($xml, 'rb')))
		{
			return array ();
		}
		while (!feof($fp))
		{
			$contents .= fread($fp, 8192);
		}
		fclose($fp);
		xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
		xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
		xml_parse_into_struct($parser, trim($contents), $xml_values);
		xml_parser_free($parser);
		if (!$xml_values)
			return; //Hmm...
		$xml_array = array ();
		$parents = array ();
		$opened_tags = array ();
		$arr = array ();
		$current = & $xml_array;
		$repeated_tag_index = array ();
		foreach ($xml_values as $data)
		{
			unset ($attributes, $value);
			extract($data);
			$result = array ();
			$attributes_data = array ();
			if (isset ($value))
			{
				if ($priority == 'tag')
					$result = $value;
				else
					$result['value'] = $value;
			}
			if (isset ($attributes) and $get_attributes)
			{
				foreach ($attributes as $attr => $val)
				{
					if ($priority == 'tag')
						$attributes_data[$attr] = $val;
					else
						$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
				}
			}
			if ($type == "open")
			{
				$parent[$level -1] = & $current;
				if (!is_array($current) or (!in_array($tag, array_keys($current))))
				{
					$current[$tag] = $result;
					if ($attributes_data)
						$current[$tag . '_attr'] = $attributes_data;
					$repeated_tag_index[$tag . '_' . $level] = 1;
					$current = & $current[$tag];
				}
				else
				{
					if (isset ($current[$tag][0]))
					{
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
						$repeated_tag_index[$tag . '_' . $level]++;
					}
					else
					{
						$current[$tag] = array (
							$current[$tag],
							$result
						);
						$repeated_tag_index[$tag . '_' . $level] = 2;
						if (isset ($current[$tag . '_attr']))
						{
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
							unset ($current[$tag . '_attr']);
						}
					}
					$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
					$current = & $current[$tag][$last_item_index];
				}
			}
			elseif ($type == "complete")
			{
				if (!isset ($current[$tag]))
				{
					$current[$tag] = $result;
					$repeated_tag_index[$tag . '_' . $level] = 1;
					if ($priority == 'tag' and $attributes_data)
						$current[$tag . '_attr'] = $attributes_data;
				}
				else
				{
					if (isset ($current[$tag][0]) and is_array($current[$tag]))
					{
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
						if ($priority == 'tag' and $get_attributes and $attributes_data)
						{
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
						}
						$repeated_tag_index[$tag . '_' . $level]++;
					}
					else
					{
						$current[$tag] = array (
							$current[$tag],
							$result
						);
						$repeated_tag_index[$tag . '_' . $level] = 1;
						if ($priority == 'tag' and $get_attributes)
						{
							if (isset ($current[$tag . '_attr']))
							{
								$current[$tag]['0_attr'] = $current[$tag . '_attr'];
								unset ($current[$tag . '_attr']);
							}
							if ($attributes_data)
							{
								$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
							}
						}
						$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
					}
				}
			}
			elseif ($type == 'close')
			{
				$current = & $parent[$level -1];
			}
		}
		return ($xml_array);
	}
}
?>

  목록  

번호 제   목 글쓴이 날짜 조회 추천수
829 HMVC 5.4 & Template_ 타로구조 만들기 [1] 타로 2012-02-02 100 0
824 CI lang팩 -> Javascript lang팩 [4] KangMin 2012-01-25 184 0
823 anchor_popup 헬퍼 화면 정 가운데 띄우기.. [0] DJ구스 2012-01-17 149 0
822 [자바스크립트] 창을 화면 정중앙에 위치하게 계산하기 [0] 웅파 2012-01-11 182 0
815 hook에서 선언한 변수를 컨트롤러에서 사용하기 [2] 웅파 2011-12-27 368 0
812 mysql 부분적인 에러 핸들링 처리 [2] EziX 2011-12-20 390 0
811 컨트롤러 외부에서의 종료방법 [1] EziX 2011-12-20 302 0
809 icodekore sms 모듈 쓰는 분들 참고하세요.. [0] namGoos 2011-12-09 514 0
803 Upgrading from 2.0.3 to 2.1.0 [5] namGoos 2011-12-06 493 0
794 .svn 폴더 삭제 하기 [7] 불의회상 2011-11-30 452 1
792 [1원] 윈도우서버+mssql 에서 CLI(Comm.. [2] 터프키드 2011-11-29 458 0
786 Form_validation 라이브러리 less_t.. [2] EziX 2011-11-17 460 0
780 1원팁. 저의 Template_ 이용방법입니다. [2] namGoos 2011-10-31 995 0
773 MYSQL 자동으로 시간 설정 [5] 불의회상 2011-10-26 659 0
767 모바일 웹사이트 개발시 참조하시면 좋을 것 같네요~ [7] 탱크 2011-10-20 781 1
764 EUC-KR 판정 방법 [3] 불의회상 2011-10-18 727 0
758 eclipse Autocomplete 업데이트 버전. [4] EziX 2011-10-14 937 0
751 글로벌 사이트를 위한 시간(GMT) 적용 [8] 웅파 2011-10-12 518 0
744 포토바다 개발 내규 문서 공개합니다. [7] namGoos 2011-10-10 845 1
735 jquery cheat 1.0 ~ 1.6 [6] 웅파 2011-10-06 759 0