I want to highlight PHP and HTML in the same code. In my attempts I experience three challenges:

  1. Seems like listings treats <?php and ?> as one large HTML tag. How to tell listings that the < in <?php is not a HTML tag?
  2. Variable values (here 23 and 42) should have a different colour... Because of what I mentioned in (1) it seems like all code between <?php and ?> is treated as HTML.
  3. Variable names... They should have their own colour. I have fixed it with emph, but there must be a better way?

All help appreciated!

Best Regards Lars

\usepackage{listings, textcomp}


\lstdefinelanguage{myhtml} {
  language = HTML,
  morecomment = [s]{<!--}{-->},
  morecomment = [l]{-->},
  otherkeywords = {=, href, target, alt, controls, action, method, src, width, height, type, class}

  captionpos = b,
  breaklines = true,
  breakatwhitespace = true;
  xleftmargin = \parindent,
  language = PHP,
  alsolanguage = myhtml,
  upquote = true,
  showstringspaces = false,
  numbers = left,
  basicstyle = \footnotesize\ttfamily\color{black},
  commentstyle = \color{codecomment},
  keywordstyle = \color{codecolor},
  numberstyle = \tiny\color{codenumber},
  stringstyle = \color{codestring}, 
  backgroundcolor = \color{codebg},
  tagstyle = \color{codecolor},
  emph = {$number},
  emphstyle = {\color{green}}


<!doctype html>
    <title> My first PHP document </title>

<h1> Welcome to my first PHP document! </h1>

  $number = 23;
  echo "Our number is $number. <br>";

  $number = 42;
  echo "Our number is now $number. <br>";

<p> Some text... </p> 

  echo "Some text... <br>";
  echo "Our variable is still accessible, our number is $number.";


  • I once took part in a discussion about HTML and PHP in listings. One conclusion is that listings does not like to process mixing code: there is no easy way to treat embedded PHP. – Symbol 1 Aug 30 '15 at 12:58
  • I think including the line moredelim=[s][\color{green}]{\$}{\ }, inside \lstdefinestyle can solve challenge no.3 – nidhin Aug 30 '15 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.