[Tex/LaTex] PHP source code in LaTeX

codelistings

Can somebody please show the correct way to display my source code in LaTeX?

I want to display the following PHP code:

$id = addslashes($_GET['id']);

I tried to do it as follows, but I get an error about a label that has not yet been referenced:

\begin{lstlisting}
$id = addslashes($_GET['id']);
\label{phpheg}
\end{lstlisting}

Best Answer

As described in the documentation of the listings package, you have to define the caption and label in the options of the lstlisting environment. This is required because any text within lstlisting is typeset, so your code prints \label{phpheg} in the PDF, instead of calling that as a LaTeX command.

\documentclass{article}
\usepackage{listings}
\begin{document}
    See Listing~\ref{phpheg} for details.
\begin{lstlisting}[caption={PHP Code},label=phpheg]
$id = addslashes($_GET['id']);
\end{lstlisting}
    More text.
\end{document}

Note: as Werner says in his comment, as everything between \begin{lstlisting} and \end{lstlisting} is printed, thus indented code is also typeset indented. As a work-around, you can (and should) write the listing without any indention (as above).

As proposed by MaxNoe, you can use the lstautogobble package as a workaround: simply add \usepackage{autogobble} and set autogobble=true in the settings of lstlistings.