drktvjp713333 2017-08-07 00:15 采纳率: 0%
浏览 36
已采纳

将HTML与PHP代码分开的简便方法

I would like to separate the html and just use echo for easier further styling/editing this html snippet, like this

<li>
  <a href="<?php echo $filepath; ?>"><?php echo $file; ?></a>
</li>

Here is my current code that works, but I can not easily edit the html inside the PHP code

<?php

$dir = ".";
$exclude = array( ".","..",".*","*.php" );
if (is_dir($dir)) {
    $files = scandir($dir);
    foreach($files as $file){
        if(!in_array($file,$exclude)){
            $filepath = str_replace(' ', '%20', $file);
            echo '<li><a href=' . $dir . '/' . $filepath . '>' . $file . '</a></li>';

        }
    }
}

?>
  • 写回答

1条回答 默认 最新

  • doupijin0397 2017-08-07 00:37
    关注

    I highly recommend PHP's alternative syntax for templating. For example

    $dir = ".";
    $exclude = array( ".","..",".*","*.php" );
    if (is_dir($dir)) {
        $files = array_diff(scandir($dir), $exclude);
        foreach ($files as $file) : ?>
        <li>
            <a href="<?= $dir ?>/<?= urlencode($file) ?>">
                <?= $file ?>
            </a>
        </li>
        <?php endforeach;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?