массив -> XML с параметрами

Jenius

Новичок
массив -> XML с параметрами

Решил изобрести велосипед в качестве тренировки, однако вот не могу сам оценить свою работу, может вы в этом мне поможете? Я не претендую на статус гуру, который сделал открытие, прежде всего делаю открытия для себя, возможно правильно, возможно нет. Вообщем киньте пожалуйста помидоры в меня с комментариями.

Я себе поставил задачу написать класс, который мог бы преобразовывать массив в XML с параметрами для любого из тега.
Сама структура массива задана строго. Например:
PHP:
       	$data = array(
         'title'=>array(array('item'=>'Title Of Page')),
         'content'=>array('attributes'=>array('type'=>'text/html', 'charset'=>'utf-8')),
         'meta'=>array(array('item'=>'some keywords', 'attributes'=>array('type'=>'keywords')), array('item'=>'some description', 'attributes'=>array('type'=>'description')))
       	);
Таким образом для каждого тега мы можем задавать параметры.

PHP:
array(
  'content'=>array('attributes'=>array('type'=>'text/html'))
)
и на выходе мы получим <content type="text/html" />

если мы хотим, что бы content содержал какие-нибудь item'ы, то пишем массив так:
PHP:
array(
    'content'=>array('attributes'=>array('type'=>'text/html'), array('item'=>'value'))
)
на выходе получим:
<content type="text/html">
<item>values</item>
</content>


и если мы захотим задать параметры и для этого item'а, то пишем

PHP:
array(
   'content'=>array('attributes'=>array('type'=>'text/html'), array('item'=>'value', 'attributes'=>array('href'=>'link', 'status'=>'active')), array('item'=>'value', 'attributes'=>array('href'=>'link', 'status'=>'active')))
)
и на выходе мы получим:
<content type="text/html">
<item href="link" status="active">value</item>
<item href="link" status="active">value</item>
</content>

Тоесть для каждого элемента можно задавать параметры.

Вот сам класс:
PHP:
<?
class Xml{

	public $xmlContainer = array();
	private $version;
	private $char;
	
	public function __construct($version, $char)
	{
		$this->version = $version;
		$this->char = $char;
	}

	private function addAttriutes($array, $parent)
	{
		if(count($array)==0 or is_string($array))
			return;
			
		foreach ($array as $key=>$value)
			$parent->addAttribute($key, $value);
	}
	
	private function array2xml($array, $key, $parent=null)
	{
		if(count($array)==0)
			return ;
			
		foreach ($array as $k=>$v)
		{
			if(NULL === $parent)
			{
				$this->addAttriutes($v['attributes'], $parent = (!isset($v[1])?$this->get($key)->addChild($k, $v[0]['item']):$this->get($key)->addChild($k)));
			}else{ 
				$this->addAttriutes($v['attributes'], $parent = (!isset($v[1])?$parent->addChild($k, $v[0]['item']):$parent->addChild($k)));
			}	
			if(!is_string($v['attributes']))
				unset($v['attributes']);
			
			if(sizeof($v)>1 and !is_string($v))
			{
				foreach ($v as $k2=>$v2)
				{
					$child = $parent->addChild('item', $v2['item']);
					$this->addAttriutes($v2['attributes'], $child);
					unset($v2['attributes']);
					unset($v2['item']);	
					$this->array2xml($v2, $key, $child);
				}
			}
			unset($parent);
		}
	}
	
	public function set($r, $array=array())
	{
		$dom = new DOMDocument($this->version, $this->char);
		$root = $dom->createElement($r);
		$dom->appendChild($root);
		$this->xmlContainer[$r] = simplexml_load_string($dom->saveXML());
		$this->array2xml($array, $r);
	}
	
	public function get($key)
	{
		return $this->xmlContainer[$key];
	}
	
	public function add()
	{}
	
	public function edit()
	{}
	
	public function delete()
	{}
}
?>


PHP:
$xml = new Xml('1.0', 'utf-8');

$xml->set('design', 
array(
         'title'=>array(array('item'=>'Title Of Page')),
         'content'=>array('attributes'=>array('type'=>'text/html', 'charset'=>'utf-8')),
         'meta'=>array(array('item'=>'some keywords', 'attributes'=>array('type'=>'keywords')), array('item'=>'some description', 'attributes'=>array('type'=>'description'))),
         'stylesheet'=>array('attributes'=>array('dir'=>'/sytles'), array('item'=>'style.css'), array('item'=>'post.css')),
         'javascript'=>array('attributes'=>array('dir'=>'/javascripts'), array('item'=>'main.js'), array('item'=>'jquery.js'))	
       	)
);
и получаем: http://daw.jenius.ru/
 
Друзья, если вы ещё не в курсе, то никто ваши трёхсотстрочные полотна кода изучать не собипается...
 

Jenius

Новичок
Автор оригинала: Вася Патриков
Друзья, если вы ещё не в курсе, то никто ваши трёхсотстрочные полотна кода изучать не собипается...
Приходилось ли решать похожую задачу? Не поделитесь ли кодом? Или какие библиотеки использовали?
 

lexaz

Новичок
Jenius, не надо одобрения искать. Если работает и тебе нра - всех в жо.

В xml::set()
PHP:
$this->xmlContainer[$r] = simplexml_load_string($dom->saveXML());
По-моему, лучше заменить на
PHP:
$this->xmlContainer[$r] = simplexml_import_dom($dom);
http://php.net/simplexml_import_dom
 
Сверху