Neskews
Neskews

Reputation: 824

CDATA does not work as expected

I wrote a function :

function wrapWithTag($tag, $data) {
  $cdata = "<![CDATA[$data]]>";
  echo "<$tag>$cdata</$tag>";
}

For instance I like to use it as

$name = 'myCellContent - <extra>';
wrapWithTag("td", $name);

The expected output would be a html table cell with string:

myCellContent - <extra>

What it actually does is printing empty cells. How can I use CDATA properly?

Edit: I have got a simple workaround:

function wrapWithTag($tag, $data) {
  $data = str_replace("<", "&lt;", $data);
  echo "<$tag>$data</$tag>";
}

However, I would prefer using a CDATA section. Feel free to post a solution :P

Upvotes: 1

Views: 1873

Answers (1)

Quentin
Quentin

Reputation: 944157

CDATA sections are a feature of XML. HTML does not support them.

XHTML does, but you must ensure the browser is parsing the document in XML mode (by setting Content-Type: application/xhtml+xml in the HTTP response headers).

In HTML, if you want to use characters which have special meaning, you must use entities such as &lt;.

PHP has the htmlspecialchars function; there's no need to roll your own with str_replace.

Upvotes: 1

Related Questions