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…
If all you want is to pass some data to JavaScript, why not just write it directly to a variable:
Anyway, if you want to do it your way, you can use
htmlspecialcharsto escape arbitrary data before putting it in an HTML attribute: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:You can then read that data in JavaScript using JSON.parse:
If your data is binary, you can base64 encode it:
Presumably there’s some way to decode this in JavaScript.