Daniel Szalay
Daniel Szalay

Reputation: 4101

Managing quotes when using CKEditor setData function

I want to print a table in PHP, each row has a button to load it's content (HTML codes) into the CKEditor instance.

 $column = '<td><a href="#" onclick="CKEDITOR.instances.editor.setData(' . "'" . $HTMLcode . "');" . '">Load</a></td>';
 echo $column;

The HTML code also contains quotes because of the CSS styles:

<p style='text-align: center;'>

I had this result, obviously it breaks the code:

<a href="#" onclick="CKEDITOR.instances.editor.setData('<p style='text-align: center;'>Great.</p>');">Load</a> 

Any workaround for this? Any help would be appreciated! Thanks in advance, Daniel.

Upvotes: 0

Views: 5337

Answers (3)

Pekka
Pekka

Reputation: 449465

The common solution is htmlentities():

$column = '<td><a href="#" onclick="CKEDITOR.instances.editor.setData(' 
         . "'" . htmlentities($HTMLcode, ENT_QUOTES) . "');" . '">Load</a></td>';

There's also addslashes() which should make the string parseable in JavaScript.

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

What speaks for choosing htmlentities() over addslashes() is the fact that in a valid HTML document, there must be no raw ampersands &. They need to be escaped as &amp; even in JavaScript statements when those are not enclosed in CDATA tags.

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

Basically, you have some quotes in a string, and want them escaped.

A solution, I suppose, would be to use something like addslashes :

$HTMLcode = "<p style='text-align: center;'>";
$column = '<td><a href="#" onclick="CKEDITOR.instances.editor.setData(' . "'" 
            . addslashes($HTMLcode) . "');" 
            . '">Load</a></td>';
echo $column;

And you'll get the following HTML code :

<td><a href="#" onclick="CKEDITOR.instances.editor.setData('<p style=\'text-align: center;\'>');">Load</a></td>

i.e. the quotes in the string that's passed to CKEDITOR.instances.editor.setData are escaped.

Upvotes: 1

Glenn
Glenn

Reputation: 8032

All you have to do is escape the quote characters in the string that you pass to the setData function.

Upvotes: 1

Related Questions