将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>';
}
}
}
?>
我想分离html并使用echo更容易进一步设计/编辑这个html片段,就像这样
&lt; li&gt;
&lt; a href =“&lt;?php echo $ filepath;?&gt;”&gt;&lt;?php echo $ file; ?&gt;&lt; / a&gt;
&lt; / li&gt;
code> pre>
这是我当前的代码有效,但我无法轻松编辑PHP内部的html 代码 p>
&lt;?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'&lt; li&gt;&lt; a href ='。 $ dir。 '/'。 $ filepath。 '&GT;' 。 $ file。 '&lt; / a&gt;&lt; / li&gt;';
}
}
}
?&gt;
code> pre>
div>
答
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;
}