39

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?

Hirvesh
  • 7,636
  • 15
  • 59
  • 72

7 Answers7

35

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>"
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

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);
Mahendra Jella
  • 5,450
  • 1
  • 33
  • 38
3

All string data must be UTF-8 encoded.

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

$out = json_encode($out);
die($out);
blumanski
  • 59
  • 1
  • 3
1

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.

Community
  • 1
  • 1
orionrush
  • 566
  • 6
  • 30
1

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/

Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
1

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.

Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
1

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.

Daan
  • 2,680
  • 20
  • 39