-1

I have dynamic content which I generate with PHP, and i want to store some various text in data attribute. Bu the problem is that i need to escape various characters that could damage my entire html

So I need to do some kind of encoding with php and then decode that string with javascript when i want to use that data, what would be the best way to do that?

And just to clarify i do not want to use any inputs or anything like that, i need to store this data in various elements for example a or div and so on...

Linas
  • 4,380
  • 17
  • 69
  • 117

1 Answers1

2

If all you want is to pass some data to JavaScript, why not just write it directly to a variable:

<html>
<head>
<script>
var data = <?php echo json_encode($data); ?>
</script>
<!-- etc. -->

Anyway, if you want to do it your way, you can use htmlspecialchars to escape arbitrary data before putting it in an HTML attribute:

<div data="<?php echo htmlspecialchars('"\'!)(@UI#_!)(@JP_!()@J'); ?>">Example</div>

If you then read that with JavaScript, it should understand the HTML encoding, so you won't need to do anything special to read it.

If your data is more complex, but not binary, you could JSON encode it, then use htmlspecialchars:

<?php
$data = array();
$data["a"] = 123;
$data["b"] = "example";
$jsonData = json_encode($data);
$escapedJsonData = htmlspecialchars($jsonData);
echo "<div data=\"$escapedJsonData\">example</div>";
?>

You can then read that data in JavaScript using JSON.parse:

var yourDiv = getDivSomehow();
var data = JSON.parse(yourDiv.getAttribute("data"));

If your data is binary, you can base64 encode it:

<?php
$data = someImage();
$encodedData = base64_encode($data);
echo "<div data=\"$encodedData\">example</div>";
?>

Presumably there's some way to decode this in JavaScript.

Community
  • 1
  • 1
Brendan Long
  • 53,280
  • 21
  • 146
  • 188
  • I'm not going to store a lot of data, just few words there and there this way it would be way easier then sending ajax request so it shouldn't hurt. And yes i guess escaping would a good way to go too. – Linas Dec 19 '12 at 21:03