nosthertus nosthertus - 1 year ago 67
PHP Question

PHP: No space between html tags when rendered from single <?php?>

this is a curious question, and i would like to know why it happens..

I am using

Yii2
framework and i created a
widget
to render a thumbnail from
Twitter bootstrap
, i have made the code to render multiple buttons if it was needed, but when i render more than 1 buttons, they seem to not be any space between each other, i checked the
html
code and it seems to be fine, i even compared the view with 2 same codes, one from
php
and another from just
html
,

this is how it looks, both have same html code, but the first one is rendered from php
enter image description here

this is how the
html
code is, both cases have the same code, difference is that the first one comes from
php


<div class="thumbnail">
<div class="caption">
<h3>testing</h3>
<p>Lorem ipsum dolor</p>
<p>
<button type="button" class="btn btn-default" name="/localhost/backend/web/site/index">Button</button>
<button type="button" class="btn btn-default" name="/localhost/backend/web/site/index">Button</button>
<button type="button" class="btn btn-default" name="/localhost/backend/web/site/index">Button</button>
</p>
</div>
</div>

<div class="thumbnail">
<div class="caption">
<h3>testing</h3>
<p>Lorem ipsum dolor</p>
<p>
<button type="button" class="btn btn-default" name="/localhost/backend/web/site/index">Button</button>
<button type="button" class="btn btn-default" name="/localhost/backend/web/site/index">Button</button>
<button type="button" class="btn btn-default" name="/localhost/backend/web/site/index">Button</button>
</p>
</div>
</div>

Answer Source

This is fixed by adding regex between each element

for example we have multiple elements being processed in a foreach loop in php and the result is concatenated in a string

<?php 

function createButtons($data)
{
    /**
     * [$html Here is where the html buttons are going to be stored]
     * @var string
     */
    $html = '';

    /**
     * This will generate Html Button for each element in the array and concatenate into $html as string like this:
     * <button><button><button><button>
     */
    foreach($data as $button)
        $html .= Html::Button($data['name'], $data['options']);

    return $html;
}

in order to make make it create a new line for each element, a "\n" which is a regex code to add a new line

<?php 

function createButtons($data)
{
    /**
     * [$html Here is where the html buttons are going to be stored]
     * @var string
     */
    $html = '';

    /**
     * This will generate Html Button for each element in the array and concatenate into $html as string like this:
     * <button>
     * <button>
     */
    foreach($data as $button)
        $html .= Html::Button($data['name'], $data['options'])."\n"; //This "\n" adds a new line in the string

    return $html;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download