📜 ⬆️ ⬇️

Conversion function stdClass to SimpleXml

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



But you can't directly bring an object into an xslt template ... I will not say for sure, but I searched before creating a new two-wheeled friend. Personal mini-era of cycling on 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 much specificity):

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, sure raw, but working and I, for the time being, have not encountered 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):
 <root> <id_book>1</id_book> <id_category_book>4</id_category_book> <sub> <id_book>1</id_book> <id_category_book>4</id_category_book> </sub> </root> 


If someone tells you more civilized decisions, I will be glad.
Well, in the absence of a chance, this function will serve someone well.

Source: https://habr.com/ru/post/132976/


All Articles