简体   繁体   中英

Change Background Color based on innerText?

I'm very new to PHP and I'm not sure how to go about this. I have a super large CSV file that is loaded as an html table using fget. How can I go through a specific column and change td background color of only the specific cells of that column that contain the word "Yes" to green?

For reference, here is my code:

<!DOCTYPE html>
<html>
<head>
<link href="stylesheets/styles.css" rel="stylesheet" />
</head>
<body>
<?php
echo "<table>\n\n";
$f = fopen("market_research.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
            if (substr($cell, 0,4) == "http") {
                echo "<td>" ."<a href='" . $cell . "'>Go!</a>";
            } else
                echo "<td>" . htmlspecialchars($cell);
        }
        echo "<tr>\n";
}
fclose($f);
echo "\n</table></body></html>";


?>

Here is my current CSS:

tr {background-color: #f7f7f7;}
body {background-color:#8b9dc3;}
td:first-child { 
        text-align: center;
        font-weight: bold;
        padding-left: 5px;
        padding-right: 5px;
}

td:nth-child(odd)
{
background-color: #FFFFFF;
}

tr:first-child {
        background-color: #FFFFFF !important;
        text-align: center;
        font-weight: bold;
        font-size: 110%;
        height: 50px;
}

td {
        padding-left: 5px;
        padding-right: 5px;
}

You can set it like this:

Hope this will help you

You need to add data-attr to your element <p> while Generating <td> s using fget()

<p data-val="Yes">Yes</p>

and your css would be like this:

p[data-val="Yes"] {background-color:green;}

Working Example

You need to set a class for these cells. This identifies a group then you can style these in your stylesheet or tags.

Add an additional IF statement that checks for your condition "$cell contain 'yes'"

You can check for a string in a string like this, this example $a is your variable and you are checking for string 'mattiscool' - if it finds it then it will output 'true'

if (strpos($a,'mattiscool') !== false) { echo 'true'; }

Instead we want to output your TD cell plus a class tag. So add part of your if statement print inside the tags - like so

<td Class="myfirstclass">

Then in your stylesheet add the styling for this class - for example.

myfirstclass{
font-family:Verdana;
font-size:16pt;
}

This what you were looking for?

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