简体   繁体   中英

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

(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 . . Eg

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

String Operators

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

You should try:

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

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

此版本不需要转义双引号:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM