1

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

\documentclass{article}
\usepackage{color}
\usepackage{listings, textcomp}

\definecolor{codecolor}{cmyk}{0.75,0.4,0,0}
\definecolor{codebg}{cmyk}{0.02,0.02,0.02,0.02}
\definecolor{codenumber}{cmyk}{0.2,0.1,0.1,0.2}
\definecolor{codecomment}{cmyk}{0.6,0,1,0}
\definecolor{codestring}{cmyk}{0,1,1,0}

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

\lstdefinestyle{customphp}{
  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}}
}

\begin{document}

\begin{lstlisting}[style=customphp]
<!doctype html>
<html>
<head>
    <title> My first PHP document </title>
</head>
<body>

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

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

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

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

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

</body>
</html>
\end{lstlisting}

\end{document}
  • 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.