Showing posts with label kohana xml module. Show all posts
Showing posts with label kohana xml module. Show all posts

2010-01-10

How to use the XML helper with XSLT

Important! All Kohana-related posts are now at http://kohana.lillem4n.se.

A friend of mine needed to use the Kohana XML-module to create XML with a XSLT-stylesheet attatched to it. This is a quick example of how you could do that. There are several other ways, but this is pretty straight forward.

The following code should be placed inside a controller method:

// First we need a DOM document do begin with
$dom = new DomDocument('1.0', 'UTF-8');

// Format the output so we can read it more easily
$dom->formatOutput = true;

// This sets the used XSL stylesheet to "example.xsl"
$dom->appendChild($dom->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="example.xsl"'));

// We need a root node in the XML
$xml_root = $dom->appendChild($dom->createElement('root'));

// This is the big XML data... database queries and other nice data should be in here
// Right now there is only a tiny bit of foo-node and bar-content
$someXmlContent = array('foo' => 'bar');

// Put the $someXmlContent inside the root-node
xml::toXML($someXmlContent, $xml_root);

// Write to screen
echo $dom->saveXML();

/** Produces
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<root>
<foo>bar</foo>
</root>
*/

// End of PHP code

Hashes: #kohana xslt #xslt #kohana xml module #kohana module #kohana #xml #php

2009-10-17

Kohana XML helper module

Important! All Kohana-related posts are now at http://kohana.lillem4n.se.

This module is actually just a helper (for now, at least). But it is very handy when working with converting various data to XML in PHP. A few examples:

Simple example of the two different return values.
As DOMDocument:
<?php
$doc = xml::toXML(array('root'=>array('fnupp'=>'dah')));
$doc->formatOutput = true;

echo $doc->saveXML();
?>


As DOMNode:
<?php
$doc = new DOMDocument();
$container = $doc->appendChild($doc->createElement('root'));

xml::toXML(array('fnupp'=>'dah'), $container);

echo $doc->saveXML();
?>


How the $container works:
xml::toXML(array('fnupp' => 'dah'))

will output:
<fnupp>dah</fnupp>

xml::toXML(array('fnupp' => 'dah'), 'root')

will output:
<root>
<fnupp>dah</fnupp>
</root>

That was just a few examples, full documentation is within the helper PHP-file. That includes passing SQL and getting it back as XML directly, working with attributes etc.

All feedback is very welcome!

Hashes: #kohana xml module #kohana module #kohana #xml #php