Back to Home

Convert stdClass to SimpleXml function

php · xslt · xml · simplexml

Convert stdClass to SimpleXml function

    For one personal project (and I just wanted to try it for a long time) I decided to use XSLT as a template engine. Everything seems to be wonderful: for XSL transformations a SimpleXml object is required, an object is also returned from the database, it would seem to be the problem, why can’t you transfer the object from the database directly to the template engine?



    But you can’t directly export the object to the xslt-template engine ... I probably won’t confirm it, but I searched before creating a new two-wheeled friend. The personal mini-era of bicycle construction for any convenient occasion has already passed.

    Therefore, the following converter function was written (by the way, I use it in codeigniter, although this does not introduce any specifics):

    if ( ! function_exists('std2simplexml'))
    {
    	function std2simplexml($object,$recursive=false)
    	{
    		$xml = new DOMDocument;
    		$root = $xml->createElement('root');
    		$xml->appendChild($root);
    		foreach ($object as $key => $child)
    		{
    			if (is_object($child))
    			{		
    				$new_xml = std2simplexml($child,true);
    				$new_xml = str_replace(array('','',''),'',$new_xml);
    				$el = $xml->createElement($key,$new_xml);
    			}
    			else
    			{
    				$el = $xml->createElement($key,$child);
    			}
    			$root->appendChild($el);
    		}
    		if (!$recursive)
    		{
    			$simple_xml = simplexml_load_string(html_entity_decode($xml->saveXml()));
    			return $simple_xml;
    		}
    		else
    		{
    			return $xml->saveXml();
    		}
    	}
    }
    


    The function is small, I'm sure it’s crude, but it’s working, and I, so far, have not encountered it so that it does not digest.

    In a simple example, it looks like this:

    Controller:
            // получаем объект книги из базы
            $book_obj = $this->book->getBookPage($book,$page/2);
            // создаем стандартный объект php
            $future_xml = new stdclass;
            // добавляем книгу
            $future_xml->book = $book_obj;
            // добавляем бла-бла
            $future_xml->blabla = $blabla;
    


    View:
            // конвертируем объект в SimpleXML
            $xml = std2simplexml($future_xml);
            // добавляем еще переменные, но уже относящиеся к шаблону
            $xml->template->base_url = base_url();
            $xml->template->title = 'Книжная полка Городецкого';
            // шаблонизатор
            $xsl = simplexml_load_file( APPPATH.'templates/index.xsl' );
    	$proc= new XSLTProcessor();
    	$proc->importStyleSheet($xsl);
    	echo $proc->transformToXML($xml);
    


    Incoming object:
    $xml = std2simplexml($future_xml);
    


      stdClass Object
      (
          [cycle_book] => Мания величия
          [title_book] => Гостья
          [sub] => stdClass Object
    	  (
    	      [id_book] => 1
    	      [id_category_book] => 4
    	      )
      )


    Result (object):
      SimpleXMLElement Object
      (
          [cycle_book] => Мания величия
          [title_book] => Гостья
          [sub] => SimpleXMLElement Object
    	  (
    	      [id_book] => 1
    	      [id_category_book] => 4
           )
      )
    


    Result (XML):
    1414


    If someone tells me more civilized solutions, I will be glad.
    Well, in the absence of some, this function will serve someone well.

    Read Next