How to echo in PHP, html tags

2020-01-26 10:18发布

I went through this before posting:

How can I echo HTML in PHP?

And still couldn't make it work.

I'm trying to echo this:

<div>
 <h3><a href="#">First</a></h3>
 <div>Lorem ipsum dolor sit amet.</div>
</div>
<div>

But I still can't find a way to make the tags "" and '' disappear, what do I have to do?

标签: php html tags echo
11条回答
我命由我不由天
2楼-- · 2020-01-26 10:54

You have a variety of options. One would be to use PHP as the template engine it is:

<?php 
  // Draw the page
?>
<div>
  <h3><a href="#">First</a></h3>
  <div>Lorem ipsum dolor sit amet.</div>
</div>
<?php
  // Done drawing.
?>

Another would be to use single quotes, which let you leave double quotes unquoted and also support newlines in literals:

<?php
  echo '<div>
  <h3><a href="#">First</a></h3>
  <div>Lorem ipsum dolor sit amet.</div>
</div>';
?>

Another would be to use a HEREDOC, which leaves double quotes untouched, supports newlines, and also expands any variables inside:

<?php
  echo <<<EOS
<div>
  <h3><a href="#">First</a></h3>
  <div>Lorem ipsum dolor sit amet.</div>
</div>
EOS;
?>
查看更多
Lonely孤独者°
3楼-- · 2020-01-26 10:54

You can replace '<' with &lt; and '>' with &gt; for ex:

echo "&lt;div&gt;";

output will be visible <div>

for longer strings make a function, for ex

function example($input) {
    $output = str_replace('>', '&gt;', str_replace('<', '&lt;', $html));
    return $output;
}

echo example($your_html);

Don't forget to put backslashes href=\"#\" or do it with single quotes href='#' or change it in a function too with str_replace

查看更多
霸刀☆藐视天下
4楼-- · 2020-01-26 10:54

This will also work fine with double quotes. To echo any html_tag with double quotes we just need to remember one thing, DO NOT USE ANY OTHER DOUBLE QUOTES(") IN THE MIDDLE.

    <?php 

     echo "
    <div>
     <h3><a href='https://stackoverflow.com/questions/3931351/how-to-echo-in-php-html-tags'>First</a></h3>
     <div>Lorem ipsum dolor sit amet.</div>
    </div>
    <div>";
?>

Notice here the link inside the php echo is enclosed within the single quotes. This is the precaution you should take while using the double quotes for this purpose.

查看更多
Fickle 薄情
5楼-- · 2020-01-26 10:55

Using the first mechanism given there will do it.

<?php
  ...
?>
<div>
 <h3><a href="#">First</a></h3>
 <div>Lorem ipsum dolor sit amet.</div>
</div>
<div>
<?php
  ...
?>
查看更多
叛逆
6楼-- · 2020-01-26 11:02

Separating HTML from PHP is the best method. It's less confusing and easy to debug.

<?php
  while($var)
  {
?>

     <div>
         <h3><a href="User<?php echo $i;?>"><?php echo $i;?></a></h3>
         <div>Lorem ipsum dolor sit amet.</div>
     </div>

<?php
  $i++;
  }
?>
查看更多
beautiful°
7楼-- · 2020-01-26 11:06

no need to use echo sir just use the tag . welcome :)

   <plaintext>
     <div>
       <h3><a href="#">First</a></h3>
         <div>Lorem ipsum dolor sit amet.</div>
     </div>
查看更多
登录 后发表回答