简体   繁体   中英

Properly Formatting HTML Inside PHP Functions

I have code like such:

function myFunction(){
    $types = getTypes();

    for ($i = 0; $i < count($types); $i++) {
        $projects = getProjects($types[i]);
        echo "<div class='block'>";
        for ($a = 0; $a < count($projects); $a++) {  
            echo "
                <p>
                    <a href='{$projects[$a]["link"]}'>{$projects[$a]["title"]}</a>
                    {$projects[$a]["description"]}

                </p>
            ";
        }
        echo " </div> ";
    }
}

And then in an html file:

<section>
    <?php myFunction(); ?>
</section>

Unless I set custom settings, beautifiers mess with the string formatting, I can't use double quotes, and all my html gets coloured the same way in any IDE. This had let me to believe this is not the way html is intended to be put in php scripts. What is the proper way of doing this?

There are many ways to write the code. For example, you can make it like:

$projects = getProjects($types[i]);
?>
<div class="block">
<?php for ($a = 0; $a < count($projects); $a++) : ?>  
    <p>
        <a href="<?php echo $projects[$a]['link'];?>"><?php echo $projects[$a]['title']; ?></a>
        <?php echo $projects[$a]['description']; ?>
    </p>
<?php endfor; ?>
</div>
<?php

I don't know if this is the "proper way", or even a good way, but it works for me. I use sprintf to create html. It compartmentalizes the quoting (at least in my brain). Something like this:

$f1 = ' <a href="%s">%s</a>%s';
echo "<p>",
    sprintf($f1,"link","title","description"),
    "</p>";

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