charlotterose23
charlotterose23

Reputation: 45

PHP - Echoing a variable in color

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>";

Upvotes: 2

Views: 945

Answers (5)

nettux
nettux

Reputation: 5406

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));

Upvotes: 0

user3111737
user3111737

Reputation:

This version does not need to escape double quotes:

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

Upvotes: 0

user2533777
user2533777

Reputation:

You should try:

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

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

Upvotes: 0

user3441996
user3441996

Reputation:

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

Upvotes: 0

faintsignal
faintsignal

Reputation: 1836

(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

Upvotes: 3

Related Questions