4

I'm trying to use htmlspecialchars but it doesn't seem to be working. I'm using OSX 10.9.1 and PHP 5.4.17. I write:

var_dump(htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES, 'UTF-8'));
echo htmlspecialchars("<a href='test'>Test</a>", ENT_XHTML, 'UTF-8');

and get:

string '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;' (length=45)
<a href='test'>Test</a

Any ideas?

RamenChef
  • 5,557
  • 11
  • 31
  • 43
Michel Lecomte
  • 333
  • 2
  • 4
  • 12
  • 1
    Why do you think it doesn't work? All seems to be right. – kelunik Feb 09 '14 at 23:27
  • 1
    Let me guess, you're viewing the rendered HTML and not the actual source. Also, `var_dump` will encode entities in an HTML context, in essence, double-encoding your string for output. – Phil Feb 09 '14 at 23:33

1 Answers1

11

It works, but you expect something else.

The output is interpreted by your browser as HTML. You can get the plain output by setting the content type to plain or using a command line.

<?php

header('Content-Type: text/plain');

var_dump(htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES, 'UTF-8'));
echo htmlspecialchars("<a href='test'>Test</a>", ENT_XHTML, 'UTF-8');
kelunik
  • 6,750
  • 2
  • 41
  • 70