繁体   English   中英

PHP函数回显HTML字符串

[英]PHP function echo with HTML string

我的HTML正文中有以下功能:

      <ul>
        <!-- Dynamic insertion of projects with PHP function -->
        <?php projectGallery(); ?>
      </ul>

这是PHP函数本身:

// This function shows a list of projects on our home page
function projectGallery(){
    include 'includes/config.php';
    $result = mysqli_query($con,"SELECT * FROM project");

    while($row = mysqli_fetch_array($result)) {

        echo "<li>
                  <a href='#' data-reveal-id='".$row['project_id']."' data-animation='fade'>
                    <div class='project'>
                      <img class='project_image' src='images/upload/".$row['project_afbeelding']. "' />
                        <h2 class='title'>".$row['project_titel']."</h2>
                    </div>
                  </a>
             </li>" ;

    };
};

好吧,如果您尽管仍然很丑陋,但仍在阅读...我的问题是,有没有更干净的方法来编写此回声部分? 没有无尽的HTML字符串。

就我个人而言,我总是这样做。 当有干净的HTML源代码时,我很喜欢

function projectGallery(){
 include 'includes/config.php';
 $result = mysqli_query($con,"SELECT * FROM project");

 while($row = mysqli_fetch_array($result)) { ?>

 <li><a href="#" data-reveal-id="<?php echo $row['project_id']; ?>" data-animation="fade">
  <div class="project">
   <img class="project_image" src="images/upload/<?php echo $row['project_afbeelding']; ?>" />
   <h2 class="title"><?php echo $row['project_titel']; ?></h2>
  </div>
 </a>
</li><?php
} ?>

这样,您的IDE可以分别识别HTML和PHP内容,从而减少出错的机会。 但是,如果扩大这个范围,则会造成混乱。 但是正如我所说,对我来说,它是很多事情之上的源代码。

您有几种选择。 首先是简单地结束PHP标记:

function projectGallery(){
include 'includes/config.php';
$result = mysqli_query($con,"SELECT * FROM project");

    while($row = mysqli_fetch_array($result))
    {
    ?>

    <li>
        <a href='#' data-reveal-id='<?php echo $row['project_id']; ?>' data-animation='fade'>

            <div class='project'>
                <img class='project_image' src='images/upload/<?php echo $row['project_afbeelding']; ?>' />
                <h2 class='title'><?php echo $row['project_titel']; ?></h2>
            </div>
        </a>
    </li>

    <?php
    };
};

另一个方法是创建一个您要回显的字符串,以便将来进行更多编辑:

function projectGallery(){
include 'includes/config.php';
$result = mysqli_query($con,"SELECT * FROM project");
$output = '';
    while($row = mysqli_fetch_array($result))
    {
    $output .= "<li>";
    $output .= "<a href='#' data-reveal-id='".$row['project_id']."' data-animation='fade'>";

    $output .= "<div class='project'>";
    $output .= "<img class='project_image' src='images/upload/".$row['project_afbeelding']. "' />";
    $output .= "<h2 class='title'>".$row['project_titel']."</h2>";
    $output .= "</div>";

    $output .= "</a>";
    $output .= "</li>";

    };
echo $output;
};

两者都有优点,以后都更易于管理和适应

在PHP模式下,绝对不要回显html代码。 这使您的代码难以读懂,您会疯狂地放置'或',并且您的IDE(如果有的话)将无法再帮助您实现HTML自动完成功能。

您应该总是这样:

<?php while($row = mysqli_fetch_array($result)) { ?>
    <li>
        <a href="#" data-reveal-id="<?=$row['project_id']?>" data-animation="fade">
            <div class="project">
                <img class="project_image" src="images/upload/<?=$row['project_afbeelding']?>" />
                <h2 class="title"><?=$row['project_titel']?></h2>
            </div>
        </a>
    </li>
<?php } ?>

因此,只要需要时就可以再次打开和关闭PHP,并使其暂时关闭。

等同于并完全相同:

<?="123"?>

但是请注意,某些Web服务器配置了短标签

试试吧

在html中:

<?php echo projectGallery(); ?>

在功能上:

return "<li><a href='#' data-reveal-id='".$row['project_id']."' data-animation='fade'><div class='project'><img class='project_image' src='images/upload/".$row['project_afbeelding']. "' /><h2 class='title'>".$row['project_titel']."</h2></div></a></li>" ;
function projectGallery(){
include 'includes/config.php';
$result = mysqli_query($con,"SELECT * FROM project");

while($row = mysqli_fetch_array($result)) {
?>
   <li>
              <a href='#' data-reveal-id='<?=$row['project_id']?>' data-animation='fade'>
                <div class='project'>
                  <img class='project_image' src='images/upload/<?=$row['project_afbeelding']?>' />
                    <h2 class='title'><?=$row['project_titel']?></h2>
                </div>
              </a>
         </li>

您可以创建一个函数,该函数接受一个文件和一个值数组,并将这些值提取到有限上下文中的变量中,包括一个文件,捕获结果输出,然后以字符串形式返回:

function render_with_values($file, array $variables = null) {

     if (!file_exists($file)) { 
         throw new Exception('Template cant be found.'); 
     }

     if ($variables !== null)
         extract($variables); //Extract array values to variables; array('foo' => 'bar') will result to $foo = 'bar'; and will be avaiable in the template you are including below but will not leak outside a function call.

     ob_start(); //Supress output

     include $file; //File 

     $content = ob_get_contents(); //Retrieve supressed output.
     ob_end_clean(); //End output supression.

     return $content;

}

将您的代码更改为:

function projectGallery(){
    include 'includes/config.php';
    $result = mysqli_query($con,"SELECT * FROM project");

    while($row = mysqli_fetch_array($result)) {

        echo render_with_values('path/to/gallery_item_template.php', $result)

    };
};

path/to/gallery_item_template.php

<li>
    <a href="#" data-reveal-id="<?php echo $project_id; ?>" data-animation="fade">
        <div class="project">
            <img class="project_image" src="images/upload/<?php echo $project_afbeelding; ?>" />
            <h2 class="title"><?php echo $project_title; ?></h2>
        </div>
    </a>
</li>

但是请认真阅读有关MVC关注点分离的概念。 您可以查看Twig等模板引擎。

不一定最漂亮,但尚未被提及,在PHP中串联某些字符串的最快方法 (性能明智)是连接数组。

function projectGallery(){

    // You should probably require that, not merely include.
    require_once 'includes/config.php';

    $result = mysqli_query($con, 'SELECT * FROM project');

    $buffer = array();

    while($row = mysqli_fetch_array($result)) {
        $buffer[] = '<li>';
        // You're using double quotes, so you can put variables directly
        // in your string, no need to concatenate with a dot. The missing
        // quotes in the array index key (project_id) are intentionnal
        // and valid PHP.
        $buffer[] = "<a href=\"#\" data-reveal-id=\"$row[project_id]\" data-animation=\"fade\">";
        $buffer[] = '<div class="project">';
        ...
        $buffer[] = '<li>';
    };

    echo implode('', $bufffer);
}

您还应该记住单引号和双引号之间的区别。 单引号不能包含变量,因此处理速度更快。 因此,如果选择使用双引号,则最好在其中包含一些变量,而不是将它们与点运算符连接在一起。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM