简体   繁体   English

php条件内的HTML

[英]HTML inside php condition

The following works fine to show a source image. 以下可以很好地显示源图像。

<html>
<h3>First Test</h3>
<img src="example1.php" />
</html>

But I wanted to validate user, then only show source image like following, 但是我想验证用户,然后只显示源图像,如下所示,

<html>
<h3>First Test</h3>

<?php
some logic = $usermatch
if($usermatch)
<img src="example1.php" />
?>

</html>

When I try the same it simply doesn't show image and doesn't accept <img src="example1.php" /> inside the PHP code. 当我尝试相同的操作时,它只是不显示图像,也不接受PHP代码中的<img src="example1.php" />

I am a beginner and just learning php and html. 我是一个初学者,只是学习php和html。

Could you please guide me how to make it work? 您能指导我如何使其工作吗?

Thanks. 谢谢。

A little change to your code, although this is rather an ugly way to do it. 对您的代码进行少许更改,尽管这样做是一种丑陋的方式。

<?php
some logic = $usermatch
if($usermatch) {
?>
<img src="example1.php" />
<?php
}
?>

You have to switch in and out of PHP mode 您必须切换进出PHP模式

<html>
<h3>First Test</h3>

<?php if($usermatch) { ?>
  <img src="example1.php" />
<?php } ?>

</html>

And some like to use echo statements, but you'll see that you get less help from editors when editing the HTML 而且有些人喜欢使用echo语句,但是您会发现在编辑HTML时,从编辑器获得的帮助较少

<html>
<h3>First Test</h3>

<?php 

if($usermatch)
     echo '<img src="example1.php" />';
?>

Don't miss the php closing and opening tags . 不要错过php的关闭打开标签 Try something like this 试试这个

<?php
some logic = $usermatch
if($usermatch) : ?>
<img src="example1.php" />
<?php
endif;
?>

Try this: 尝试这个:

<?php
some logic = $usermatch
if($usermatch) { ?>
  <img src="example1.php" />
<?php
}
?>

The problem is that you are mixing your HTML & PHP code. 问题是您正在混合HTML和PHP代码。 It is perfectly aceptable to have HTML code in your PHP file, but you need to close the PHP code block before so that the interpreter understands that it is not code you intend to run. 在您的PHP文件中包含HTML代码是完全可以接受的,但是您需要先关闭PHP代码块,以便解释器理解它不是您打算运行的代码。

Might as well add to all of the answers: 可能还会添加所有答案:

<html>
<h3>First Test</h3>

<?php echo $usermatch ? '<img src="example1.php" />' : ''; ?>

</html>

Use the following: 使用以下内容:

<html>
<h3>First Test</h3>

<?php
    some logic = $usermatch
    if($usermatch) {
         print '<img src="example1.php" />'
    }
 ?>

</html>

or you can use another way to print html tags in php: 或者您可以使用另一种方式在php中打印html标签:

<html>
 <h3>First Test</h3>
 <?php
 some logic = $usermatch
      if($usermatch) { 
 ?>
 <img src="example1.php" />
 <?php } ?>
 </html>

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

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