Hello can somebody please show the correct way to display my source code in Latex

The following code I want to display as php code

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

How can I display the above code in Latex as source code ? In My document .

I tried the below but get an error about a label not yet been referenced

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

migrated from stackoverflow.com Oct 9 '16 at 8:03

This question came from our site for professional and enthusiast programmers.

  • Welcome to TeX.SE! Your post was migrated here from Stack Overflow. Please register on this site, too, and make sure that both accounts are associated with each other (by using the same OpenID), otherwise you won't be able to comment on or accept answers or edit your question. – Werner Oct 9 '16 at 15:18

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.

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

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.

  • Be aware that indenting your lstlisting environment as well as the code contained within it may result in indentation when setting it. – Werner Oct 9 '16 at 4:54
  • there's lstautogobble – MaxNoe Oct 9 '16 at 10:10
  • Thanks for you inputs, I tried to make that more clear in my answer. – hbaderts Oct 9 '16 at 15:15

Your Answer

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