Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTML Code Through JSON

I've got a php script which generates HTML content. Is there a way to send back that HTML content through JSON to my webpage from the php script?

like image 237
Hirvesh Avatar asked Feb 21 '11 10:02

Hirvesh


People also ask

Can JSON hold HTML?

The problem with HTML inside JSON is that HTML elements have properties that must use double quotes. But as soon as you insert double quotes it's going to cause syntax error because JSON can only do double quotes.

How escape HTML tag JSON?

However, if your data contains HTML, there are certain things that you need to do to keep the browser happy when using your JSON data within Javascript. Escape the forward slash in HTML end tags. <div>Hello World!


1 Answers

Yes, you can use json_encode to take your HTML string and escape it as necessary to be valid JSON (it'll also do things that are unnecessary, sadly, unless you use flags to prevent it). For instance, if your original string is:

<p class="special">content</p> 

...json_encode will produce this:

"<p class=\"special\">content<\/p>" 

You'll notice it has an unnecessary backslash before the / near the end. You can use the JSON_UNESCAPED_SLASHES flag to prevent the unnecessary backslashes. json_encode(theString, JSON_UNESCAPED_SLASHES); produces:

"<p class=\"special\">content</p>" 
like image 135
T.J. Crowder Avatar answered Sep 21 '22 08:09

T.J. Crowder