Convert stdClass to SimpleXml function
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):
1 4 1 4 If someone tells me more civilized solutions, I will be glad.
Well, in the absence of some, this function will serve someone well.