PowerMan2015
PowerMan2015

Reputation: 1418

php echo outputting html as text

I am trying to use php to construct html code containing onclick="Javascript" within

i keep getting an error saying that i am missing a } within the console, however this is not the case.

despite the error the site displays perfectly

I then followed this post

How should I echo a PHP string variable that contains special characters?

and used the method htmlentities

at first it appeared to work correctly however i must have changed something because now it outputs the html string as text and not displaying the element

this issue is present across different platforms/browsers, so i dont believe that it is cache related problem.

there are other elements within the php script that output the html correctly, it just appears that its this line.

Thanks in advance

 echo htmlentities('<h2 class="page_title">' . $db_field['Title'] . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');

Upvotes: 0

Views: 378

Answers (3)

Paul Carlton
Paul Carlton

Reputation: 2993

Whenever you call htmlentities(), whatever in it will be translated into characters that the browser interprets as literal symbols to show. This is how we can tell browsers to display HTML and code without actually interpreting it. It also allows us to show symbols we don't want the browser to accidentally parse. If you have a string containing HTML that you want to be interpreted by the browser, DO NOT use htmlentities().

You don't want:

print htmlentities("<h1>I have a < and > sign I don't want interpreted</h1>");

You actually do want:

print '<h1>' . htmlentities("I have a < and > sign I don't want interpreted") . '</h1>';

Read the docs: http://php.net/manual/en/function.htmlentities.php

Upvotes: 0

Lo&#239;c
Lo&#239;c

Reputation: 11943

Why such violence?

here is how to output templates using PHP :

<?php
//blablabla my php stuff here...
?>
<h2 class="page_title">
  <?=htmlentities($db_field['Title'])?>
</h2>
<a onclick="showAndroidToast('<?=$_SESSION[\'user_id\']?>','<?=$db_field[\'ID\']?>');
  <img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px">
</a>

Upvotes: 0

Barmar
Barmar

Reputation: 780879

You should not use htmlentities() on strings that you actually want to be interpreted as HTML, since it will convert the < and > into entities so they display literally. Just call it on the variables that you don't want interpreted:

echo '<h2 class="page_title">' . htmlentities($db_field['Title']) . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');

Upvotes: 1

Related Questions