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";
$json_array=array(
'content'=>50,
'html_content'=>$html_content
);
echo json_encode($json_array);
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.
All these answers didn't work for me.
But this one did:
json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);
Thanks to this answer.
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);
In PHP:
$data = "<html>....";
exit(json_encode($data));
Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/
Source: Stackoverflow.com