2

Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.

My code without colour:

<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo  fgets($file);
}
fclose($file);
?>

I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?

The code I tried but doesn't work:

echo "<div style=\"color: red;\">fgets($file)</div>";
2
  • 4
    echo "<div style=\"color: red;\">" . fgets($file) . "</div>"; Commented Mar 22, 2014 at 12:37
  • Hint: use . to concatentate two strings. Hint#2: code inside string literals won't execute. Commented Mar 22, 2014 at 12:37

5 Answers 5

3

(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.

echo "<div style=\"color: red;\">" . fgets($file) . "</div>";

String Operators

Sign up to request clarification or add additional context in comments.

1 Comment

fyi, it's better to use single/double quotes so you don't have to escape quotes.
0

Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.

Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span

Comments

0

You should try:

<div style="color: red;"><?= fgets($file);?></div>

Note: <?= is an short hand method for <?php echo fgets($file);?>

Comments

0

This version does not need to escape double quotes:

echo '<div style="color:red;">' . fgets($file) . '</div>';

Comments

0

You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:

echo sprintf("<div style='color: red;'>%s</div>", fgets($file));

This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:

echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.