Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output HTML in JSON string generated by PHP

I have some PHP that outputs json.

<?php
$html = utf8_encode($gegevens['tekst']);
$html = htmlentities($html);
//$html = htmlspecialchars($gegevens['tekst'], ENT_QUOTES, 'UTF-8');
echo json_encode(array( 'titel' => $gegevens['titel'], 'html' => $html ));
?>

The output will be like:

{"titel":"Here comes the title","html":"<strong>Here is the HTML<\/strong>\n<br \/>\n<br \/>\n     And some more."}

And the jQuery/Ajax will be:

$.ajax({
                            type: "GET",
                            url: "content/popup.php?id=" + id2,
                            dataType: 'json',
                            crossDomain: true,
                            success: function(json) {
                            var titel = json['titel'];
                            var html = json['html'];


function ContentTonen()
{
                                // Div's legen van content
$('.popup_home_head_inside').empty();
$('.popup_home_content_inside').empty();

$('.popup_home_head_inside').html(titel);
var html2 = html.replace(/\"/g, "");
//$('.popup_home_content_inside').html(html2);
$('.popup_home_content_inside').html(html2);

And the HTML output is:

<strong>Some HTML</strong> <br /> Some more text.

So it will not process as HTML.

Can you help me out?

like image 522
Daan Avatar asked Aug 07 '13 10:08

Daan


1 Answers

You need not escape the html with htmlentities on server side.

Remove the $html = htmlentities($html); from your php file.

Reason: htmlentities will convert

<strong>Some HTML</strong> <br /> Some more text.

to

&lt;strong&gt;Some HTML&lt;/strong&gt; &lt;br /&gt; Some more text.

which when included in html will display:

<strong>Some HTML</strong> <br /> Some more text.
like image 53
Jithesh Avatar answered Oct 17 '22 01:10

Jithesh