Search code examples
phphtmlonclickonmouseover

Writing a dynamic Hover tabs in html using php


I am following the link: Hover Tabs .I am reading a file content want to make it as id print tabcontent accordingly.

My file: NamingClass.txt contains:

Bicycle
MountainBike
Test

My php code contain:

<div class="tab">
    <?php
    $filename="NamingClass.txt";
    $Content=file($filename);
    $NoOfLine=count(file($filename));
    for($i=0;$i<$NoOfLine;$i++)
    {
            $cont=$Content[$i];
            $jid="'$cont'";
            echo '<button class="tablinks" onmouseover="openCity(event, '.$jid.')">'.$cont.'</button>';
    }
        echo '</div>';
        for($i=0;$i<$NoOfLine;$i++)
        {
                $cont=$Content[$i];
                echo '<div id="'.$cont.'" class="tabcontent">
                  <h3>'.$cont.'</h3>
                  <p> Content1 code.....</p>
                </div>';
        }
?>

But the tabcontent value is not printing. I think the mistake I am doing here is $jid because in original code

<button class="tablinks" onmouseover="openCity(event, 'London')">London</button>

Inorder to print 'London' in php echo, I have used $jid="'$cont'";

echo '<button class="tablinks" onmouseover="openCity(event, '.$jid.')">'.$cont.'</button>';

I have tried all the possibilities but it is not printing the tabcontent Please suggest something.


Solution

  • When you assign $NoOfLine, use count ( $Content );, not count ( file ( $filename ) ); Also, both loops seem to be doing the same thing, so I would combine them, then echo your first code block in that for() loop and also build your second echo in that first for() loop and then echo that built up data after the for() loop is done, also file() doesn't remove EOL(s) so I would use array_map with trim||rtrim() when you slurp up your file(). I also think its wasteful to rewrite / copy variables when you already have the variable in "$Content[$i]"...

    Example...

    $filename = "NamingClass.txt";
    
    $Content  = array_map ( 'rtrim', file ( $filename ) );
    
    $NoOfLine = count ( $Content );
    
    $secondL  = '';
    
    for ( $i = 0; $i < $NoOfLine; $i += 1 )
    {
        echo '<button class="tablinks" onmouseover="openCity(event, \'' . $Content[$i] . '\')">' . $Content[$i] . '</button>';
    
        $secondL .= '<div id="' . $Content[$i] . '" class="tabcontent">
                  <h3>' . $Content[$i] . '</h3>
                  <p> Content1 code.....</p>
                </div>';
    }
    
    echo '</div>';
    
    echo $secondL;