PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Formatting to XML

Zend_Log_Formatter_Xml formats log data into XML strings. By default, it automatically logs all items in the event data array:

<?php
$writer 
= new Zend_Log_Writer_Stream('php://output');
$formatter = new Zend_Log_Formatter_Xml();
$writer->setFormatter($formatter);

$logger = new Zend_Log();
$logger->addWriter($writer);

$logger->info('informational message');

The code above outputs the following XML (space added for clarity):

<logEntry>
  <timestamp>2007-04-06T07:24:37-07:00</timestamp>
  <message>informational message</message>
  <priority>6</priority>
  <priorityName>INFO</priorityName>
</logEntry>

It's possible to customize the root element as well as specify a mapping of XML elements to the items in the event data array. The constructor of Zend_Log_Formatter_Xml accepts a string with the name of the root element as the first parameter and an associative array with the element mapping as the second parameter:

<?php
$writer 
= new Zend_Log_Writer_Stream('php://output');
$formatter = new Zend_Log_Formatter_Xml('log',
                                        array(
'msg' => 'message',
                                              
'level' => 'priorityName')
                                       );
$writer->setFormatter($formatter);

$logger = new Zend_Log();
$logger->addWriter($writer);

$logger->info('informational message');

The code above changes the root element from its default of logEntry to log. It also maps the element msg to the event data item message. This results in the following output:

<log>
  <msg>informational message</msg>
  <level>INFO</level>
</log>

Zend Framework