Kevin Damstra
Kevin Damstra

Reputation: 125

PHP function echo with HTML string

I have this function in my HTML body:

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

And this is the PHP function itself:

// 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>" ;

    };
};

Well, if you're still reading despite the ugliness... My question is, would there be a cleaner way to write this echo part? Without the endless HTML string.

Upvotes: 0

Views: 6941

Answers (7)

Steini
Steini

Reputation: 2783

You should never echo html code at all in PHP mode. This makes your code hard readable, you get crazy placing ' or " and your IDE (if you have one) cannot help you with HTML auto completion anymore).

You should always go like this:

<?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 } ?>

So just open and close PHP again whenever you need it and leave it closed for a while.

Is equivalent to and exactly the same as:

<?="123"?>

But beware that some webservers are configured that short tags

Upvotes: 1

rixo
rixo

Reputation: 25001

Not necessarily the prettiest but it has not been mentioned yet, the fastest way (performance wise) way to concatenate some strings in PHP is to join an array.

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);
}

You should also keep in mind the difference between single and double quotes. Single quotes are processed faster because they can't contain variables. So, if you chose to use double quotes, you'd better have some variables in it instead of concatenating them with the dot operator.

Upvotes: 0

Bez Hermoso
Bez Hermoso

Reputation: 1132

You can create a function that takes a file and an array of values and extract those values into a variables within a confined context, include a file, capture the resulting output, and return as string:

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;

}

The change your code to:

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)

    };
};

In 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>

But seriously, read up on MVC and the concept of separation of concerns. You could check out templating engines like Twig.

Upvotes: 0

Onur Sevik
Onur Sevik

Reputation: 75

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>

Upvotes: 0

niaccurshi
niaccurshi

Reputation: 1295

You have a few options. The first is to simply end the PHP tags:

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
    };
};

Another would be to create a string that you echo, which allows for greater editing in the future:

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;
};

Both have their merits, both are easier to manage and adapt at a later date

Upvotes: 3

Mave
Mave

Reputation: 2516

Personally, I always do this. I love when there's a clean HTML source.

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
} ?>

That way, your IDE will recognize both the HTML and PHP content separately, giving you less chance of errors. This, however, if expanded upon, is a source of clutter. But as I said, for me, it's the source code above a lot of things.

Upvotes: 2

Sorbo
Sorbo

Reputation: 339

try it

In html:

<?php echo projectGallery(); ?>

In function:

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>" ;

Upvotes: 0

Related Questions