简体   繁体   中英

Add PHP code to dynamically generated HTML data

I am trying to make a website which will basically have a lot of buttons that will execute a particular PHP file on click and show their results on an empty box on the same screen. These PHP files are present in a directory test_scripts in the same directory as index.php .

I thought that the obvious step would be to create a loop that will iterate over those files and create their ui dynamically. So I wrote the following PHP code in the middle of index.php

#Index.php
...
 <?php
    $dir_itr = new DirectoryIterator("test_scripts");
    foreach ($dir_itr as $file) {
        if ($file->isFile()) {

            $filename = $file->getFilename();
            $formattedFileName =
                '<button
                     class="box button is-large is-fullwidth is-primary is-light"
                     onclick="loadScriptFileData($filename)">
                               $filename
                 </button>';
            print $formattedFileName;
        }
    }
?>
...

The loadScriptFileData() is a JavaScript function written in a script tag present in head:

<!--index.php-->

<script>
    function loadScriptFileData(filename) {
        alert(filename);
    }
</script>

The for each loop is running correctly, but the JavaScript function and the generated HTML is not working correctly. There are the expected number of buttons on the page, but each button just has the name as the word "$filename" and not the actual expected filename. The case is worse with JavaScript, which straight out does not work and gives the error in the console as Uncaught ReferenceError: $filename is not defined at HTMLButtonElement.onclick ((index):71)

Why is the $variable not getting converted to a string? I even tried the toString() function, but still no good. Am I doing it wrong?

Variables are not parsed/interpreted when using single quotes.

Replace

$formattedFileName= '<button 
  class="box button is-large is-fullwidth is-primary is-light" 
  onclick="loadScriptFileData($filename)">$filename</button>';

with

$formattedFileName= "<button 
  class=\"box button is-large is-fullwidth is-primary is-light\" 
  onclick=\"loadScriptFileData('$filename')\">$filename</button>";

and everything should be working as expected.

Another option (which is my personal preference) is to end the PHP block when outputting HTML and just echo the PHP variables where needed:

if ($file->isFile()) {
    $filename = $file->getFilename();
    // Let's end the PHP block
    ?>

        <button class="box button is-large is-fullwidth is-primary is-light"
            onclick="loadScriptFileData('<?= $filename ?>')">
            <?= $filename ?>
        </button>

    <?php // Open the PHP block again
}

The upside with this is that IDE's will syntax highlight the code properly (which most IDE's don't do for HTML inside quotes in PHP).

You also don't need to escape quotes or manually print the content since it gets outputted straight away.

It's a personal preference, but I recommend either concatenation or curly braces:

Using curly braces (note: must wrap with double quotes):

$formattedFileName =
    "<button
        class="box button is-large is-fullwidth is-primary is-light"
        onclick="loadScriptFileData({$filename})">
        {$filename}
    </button>";

Using concatenation:

$formattedFileName =
    '<button
        class="box button is-large is-fullwidth is-primary is-light"
        onclick="loadScriptFileData(' . $filename . ')">
        ' . $filename . '
    </button>';

Yes, you can use variables in a string in PHP if you use double quotes, and there are certainly many people that like doing that. To me, it seems cleaner and less error-prone to use one of these two methods.

Using double quotes causes you to either use single quotes for HTML attributes or forces you to escape them.

Not using concatenation or curly braces can cause issues if you don't want a space after the variable:

$var = 'Pizza';
echo "$vars are awesome!" // Not the best example, but you get the idea

Bottom line, it's a personal preference. But as stated in the other answer, you can't use variables in a string if enclosed by single quotes.

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