79

I work a lot in mixed HTML and PHP and most time I just want solid HTML with a few PHP variables in it so my code look like this:

<tr><td> <input type="hidden" name="type" value="<?php echo $var; ?>" ></td></tr>

Which is quite ugly. Isn't there something shorter, more like the following?

<tr><td> <input type="hidden" name="type" value="$$var" ></td></tr>

This is possible to but you get stuck with the "" (you have to replace them all with '') and the layout is gone

echo "<tr><td> <input type="hidden" name="type" value="$var" ></td></tr>"

Is there anything better?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
matthy
  • 8,144
  • 10
  • 38
  • 47
  • Keep in mind that PHP is faster with single quotes than double, and if you have to, use echo ' '; – Lucian Minea Oct 11 '16 at 12:51
  • 4
    @LucianMinea They are the same speed. Single quotes and double quotes are just *quotes*, neither is "faster". This is often repeated misinformation and it's completely wrong. – user229044 Sep 12 '17 at 12:16
  • 3
    It is faster with single, and it's easy to see on large code blocks. The reason is that PHP automatically does a "cleaning" of double quotes on runtime, but it doesn't on single quotes. Using double quotes also makes the code in the question stuck, because the quotes just close in a wrong position. Besides, I was just trying to give the man a solution, with a little of explanation. I do this from '91 so I thing I know my grounds. – Lucian Minea Sep 13 '17 at 07:22

7 Answers7

106

There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:

<input type="hidden" name="type" value="<?= $var ?>" >

which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:

<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>

That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • 5
    @code_burgar Short tags will not be removed from PHP6, nor are they currently deprecated. – user229044 Jan 27 '10 at 21:16
  • 1
    Hmm, I could be wrong, but I was pretty sure they are getting removed. Even if they are staying, using them is, at best, a doubtful practice. = whoops. Not to mention they are disabled by default on some servers. – code_burgar Jan 27 '10 at 21:32
  • 2
    @code_burgar Don't write XML inside your PHP scripts, XML encode your data and write the resulting output. I've never encounter a server with short_open_tags disabled. – user229044 Jan 27 '10 at 21:38
  • I've seen a number of servers that had them disabled by default. – code_burgar Jan 27 '10 at 21:49
  • 5
    No. Short echos are enabled **by default, regardless of ini settings, in PHP >= 5.4**. No need to set `short_open_tag` any more, you can feel free use your `=` and `?>` for clean code in your views. Even back in 2010, short tags ever being deprecated was complete and utter rubbish. – Jimbo Apr 29 '13 at 11:44
  • 3
    To echo @Jimbo's point, `` and `=` are often confused. The former are discouraged, the latter are fine, and as of PHP 5.4 the latter are always available (see http://www.php.net/manual/en/ini.core.php#ini.short-open-tag ) You only have to be careful to make sure `short_open_tag` is on (it is `PHP_INI_ALL`, meaning it can be switched on in your script) if using php 5.3 and earlier. – Darren Cook Dec 07 '13 at 03:15
26

Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.

echo <<<MYTAG
  <tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;
code_burgar
  • 12,025
  • 4
  • 35
  • 53
5

I really think you should adopt Smarty template engine as a standard php lib for your projects.

http://www.smarty.net/

Name: {$name|capitalize}<br>
gcb
  • 13,901
  • 7
  • 67
  • 92
  • 9
    What are your arguments in favour? – Rob Jan 27 '10 at 21:43
  • 3
    arguments in favour: - separation of php code from html (better for maintenance) - a smarty template will display in a browser as is. (front end designers with no programing experience can make better sense of it) - caching. (you can hold multiple cached copies of your page according to the inputs, which can be much faster than generating the whole page again) disadvantages - smarty is a little too powerfull, and programers can put too much logic into a template... but at least it is display logic – Bingy Jan 28 '10 at 03:10
  • Exactly what he is saying. You don't write a database connection class to connect to your database right? why do you write a template engine to do templates? – gcb Jan 28 '10 at 21:10
  • Templating system is good when STRUCTURE, STYLE and PROGRAMMING are done by more (different) people, for little projects - when there is only one or two programmers - it can even cost you time. – jave.web Jan 05 '14 at 18:18
  • @jave.web same with a data base connector class. It is all about trade offs. and for the question, using smarty is years ahead of php short tag with very little disadvantages. – gcb Jan 05 '14 at 21:00
2

I'd advise against using shorttags, see Are PHP short tags acceptable to use? for more information on why.

Personally I don't mind mixing HTML and PHP like so

<a href="<?php echo $link;?>">link description</a>

As long as I have a code-editor with good syntax highlighting, I think this is pretty readable. If you start echoing HTML with PHP then you lose all the advantages of syntax highlighting your HTML. Another disadvantage of echoing HTML is the stuff with the quotes, the following is a lot less readable IMHO.

echo '<a href="'.$link.'">link description</a>';

The biggest advantage for me with simple echoing and simple looping in PHP and doing the rest in HTML is that indentation is consistent, which in the end improves readability/scannability.

Community
  • 1
  • 1
Niels Bom
  • 8,728
  • 11
  • 46
  • 62
  • 4
    Nobody should *ever* use that question as a reference, it's a steaming heap of misinformation and subjective opinion. – user229044 Apr 29 '13 at 12:34
  • @meagar: Exactly! Not to mention, a comment there highlights [this link](http://php.net/manual/en/function.echo.php) specifies that short echo tag is detached from short open syntax from php5.4 onward. This is what it (the manual at the end of the above link) says. "**echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.**" – Romeo Sierra Sep 12 '17 at 05:08
1

In a php section before the HTML section, use sprinf() to create a constant string from the variables:

$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");

Then in the HTML section you can do whatever you like, such as:

<p>$mystuff</p> 
Coly Moore
  • 19
  • 2
1

There are plenty of templating systems that offer more compact syntax for your views. Smarty is venerable and popular. This article lists 10 others.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
1

I was about to use a template engine like Smarty but my use case is very basic (rendering PHP variables in my emails templates), so I created this class... I hope this can help:

class HtmlRender
{
    public function __construct($template, array $data)
    {
        $this->template = $template;
        $this->data = $data;
    }
    private static function fileGetContentsUFT8($file)
    {
        $content = file_get_contents($file);
        return mb_convert_encoding($content, "HTML-ENTITIES", "UTF-8");
    }
    public function render()
    {
        $template = self::fileGetContentsUFT8($this->template);
        foreach ($this->data as $key => $value) {
            $template = str_replace('{{ ' . $key . ' }}', $value, $template);
        }
        return $template;
    }
}

And this is how I use:

 $renderer = new HtmlRender(
            __DIR__ . '/templates/account.create.html',
            [
                'name' => $clientName,
                'email' => $clientEmail
            ]
  );
  $body = $renderer->render();

And inside your Html use the following syntax :

<p>Your name is: <span> {{ name }} </span></p>
<p>Your email is: <span> {{ email }} </span></p>
Youssef Elmoumen
  • 468
  • 4
  • 10