5

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?

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

5 Comments

How do I prepare the html for JSON then? Stripslashes does not work.
What kind of preparation do you mean?
When I insert the HTML directly into the JsonEncode it returns null. Because it is not valid JSON. With htmlentities JsonEncode accepted the string as valid JSON. But which function should I use to prepare the HTML to be valid JSON?
Please try this. <?php $html = utf8_encode($gegevens['tekst']); echo json_encode(array( 'titel' => $gegevens['titel'], 'html' => $html )); ?>
So simple and so effective. Thanks you saved me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.