Syntax Highlighting in Yii

Site has moved

This site has moved to a new location. Visit the new site at

By Ronald van Belzen | April 29, 2013

Syntaxhighlighting is not difficult in Yii, but I was unable to find any examples on the web. CTextHighlighter is well documented, but a working example is sometimes helpful.

On my website I use the CKEditor with the help of the editMe extension to edit text. In the editor I enter the <pre> tag with the attribute "lang" to enclose code. For viewing the text I use the following jQuery script to change the displayed code:

function setSyntax(id) { 
  var content = $('#'+id).html(); 
  var lang = $('#'+id).attr('lang'); 
    url: url, 
    type: "POST", 
    dataType: "json", 
    data: {
      "id" : id, 
      "lang" : lang, 
      "content" : content 
    success: function(data){
    error: function(error){
      console.log("Error:"); console.log(error); 

  $('pre').each(function(n) { = 'code_'+n; 

The script reads all code enclosed inside <pre> tags and sends it to the server with Ajax calls. The returned content is used to replace the <pre> tags together with their content.

On the server side the controller action handles the request:

public function actionSyntax() { 
  $json = array(); 
  $json['id'] = $_POST['id']; 
  $language = $_POST['lang']; 
  $content = $_POST['content']; 
  $content = str_replace('<br>', '', $content); 
  $content = str_replace('<p>', '', $content); 
  $content = str_replace('&lt;', '<', $content); 
  $content = str_replace('&gt;', '>', $content); 
  $highlighter = new CTextHighlighter; 
  $highlighter->showLineNumbers = true; 
  $highlighter->language = $language; 
  $content = $highlighter->highlight($content); 
  $json['content'] = $content; 
  echo json_encode($json); 

After some cleaning up of the content it is CTextHighlighter that does the actual highlighting with "$highlighter->highlight($content)".