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?
-
2If you're just sending markup back, why JSON encode at all? – dartacus Feb 21 '11 at 10:43
-
because a plugin and it has some limitations... – Hirvesh Feb 21 '11 at 10:54
-
You might want a conditional action based on the response i.e if operation successful then show HTML, if failed show appropriate error message – nmcilree Feb 15 '19 at 15:27
7 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>"

- 1,031,962
- 187
- 1,923
- 1,875
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);

- 5,450
- 1
- 33
- 38
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);

- 59
- 1
- 3
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.
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/

- 17,396
- 5
- 54
- 76
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.

- 17,460
- 16
- 70
- 118
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.

- 2,680
- 20
- 39