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?


Yes, you can use json_encode to take your HTML string and escape it as necessary.

Note that in JSON, the top level item must be an array or object (that's not true anymore), it cannot just be a string. So you'll want to create an object and make the HTML string a property of the object (probably the only one), so the resulting JSON looks something like:

{"html": "<p>I'm the markup</p>"}

Just to expand on @T.J. Crowder's answer.

json_encode does well with simple html strings, in my experience however json_encode often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.

Do Like this

1st put all your HTML content to array, then do json_encode

$html_content="<p>hello this is sample text";

echo json_encode($json_array);

All string data must be UTF-8 encoded.

$out = array(
   'render' => utf8_encode($renderOutput), 
   'text' => utf8_encode($textOutput)

$out = json_encode($out);


$data = "<html>....";

Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery:

You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.

Need Your Help

The user or administrator has not consented to use the application - Send an interactive authorization request for this user and resource

javascript c# azure dynamics-crm

We're doing this CRM Web API project. The project logs-into Dynamics CRM online instance and gets the list of accounts.