Output formats


Description


The Format class makes it easy to convert data to different formats (JSON, XML and CSV).


Methods


json(array $data)


The json method returns a JSON representation of the array.


If $_GET['jsoncallback'] is set then the method will return JSON with padding a.k.a. JSONP
echo Format::json($array);

xml(array $data [, string $rootNode = 'items' [, string $unknownNode = 'item' [, string $charset = MAKO_CHARSET]]])


The xml method returns a XML representation of the array.


echo Format::xml($array);

csv(array $data)


The csv method returns a CSV representation of the array.


echo Format::csv($array);

Examples


Using the Format class in combination with custom routes provides an easy way of delivering content in different formats.


'custom_routes' => array
(
	'news/article/([0-9]+).(json|xml|csv)' => 'news/article/$1/$2',
),

Now all we have to do in our controller is this:


public function action_article($id, $format)
{
	$article = $this->news->get($id);

	if(!$article)
	{
		throw new \mako\RequestException(404);
	}

	header('Content-Type: ' . Config::get("mimes.{$format}") . '; charset=' . MAKO_CHARSET);

	return Format::$format($article, 'article');
}