che-azeh che-azeh - 1 year ago 77
PHP Question

htmlentities works on browser only when called twice

Now here's a totally weird behaviour I'm experiencing with PHP:

doesn't seem to work when called; Thus, when I do:

echo htmlentities("<iframe>");

the browser outputs the string argument unescaped, i.e.

However, when I call the function twice, it works:

echo htmlentities(htmlentities("<iframe>"));

giving me:

I noticed the weird behaviour from this answer where the user expressed the same confusion.

Now I have two issues with using this "answer which works": firstly, I know this is a strange behaviour, and there's no guarantee that this strangeness will be replicated (I hope it isn't!) when my code is exported to another server. Secondly, why this behaviour in the first place?

So my issue: I would love to know the origin of this behaviour and what to do about it.

It's a shame a lot of you won't be able to verify my problem, given I'm working on my localhost and
works fine on other servers.

Answer Source

I think you're getting confused by the browser interpreting the results

echo htmlentities(htmlentities("<iframe>"));

Produces (raw output)


Pass one converts the <> into &lt;iframe&gt;
Pass two is converting the & into &amp;

When your browser renders it, the &amp; is then rendered as &, producing the output in your question. if you view the source you'll see what I posted above.

So it's working as intended. See a demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download