Somk
Somk

Reputation: 12047

Encode HTML for JSON string

I am storing html in a mysql database as raw html. I am pulling the contents and placing it into an array as follows. The array is the json_encoded, but if there is any double quotes or urls then the javascript displaying the JSON string breaks.

Is it possible to encode html to work through JSON?

Here is an extract of what I am using

    <?php
    $rows = array();
    $sql ="SELECT html FROM table";

    try {  
        $sth = $dbh->query($sql); 
        while($r = $sth->fetch(PDO::FETCH_OBJ)) {
            $rows[] = $r;
        }
    }
    catch(PDOException $e) {  
        echo "I'm sorry, Dave. I'm afraid I can't do that. $e";  
    } 
    ?>

var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');

The json string currently outputting throws a javascript error saying unexpected <

[{"html":"<a href="http:\/\/www.url.com">\n<img src="http:\/\/www.url.com\/img\/logo.png">\n<\/a>"}]

Please no lectures on why this may be a bad thing. This is what my client has requested specifically and I just need to know if it is possible.

Upvotes: 2

Views: 11377

Answers (4)

Robert
Robert

Reputation: 20286

I agree with Mark B's answer but you could use fetchAll() and json_encode() the result of this function. Why do you use PDO Object fetching instead of array fetching?

<?php
$rows = array();
$sql ="SELECT hmtl FROM table";

try {  
    $sth = $dbh->query($sql); 
    $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {  
    echo "I'm sorry, Dave. I'm afraid I can't do that. $e";  
} 
?>

var json = <?= json_encode($rows); ?>;

Moreover consider getting it via AJAX.

Upvotes: 3

Marc B
Marc B

Reputation: 360782

There's no need for the json.parse business. JSON IS valid javascript after all, so a simple

var json = <?php echo json_encode($rows); ?>;

is all you need.

Upvotes: 2

Kreshnik Hasanaj
Kreshnik Hasanaj

Reputation: 5005

Before filling the JSON object, you could use htmlentities() to convert all applicable characters to HTML entities, and then when printing them out just use html_entity_decode() if you use an ISO standard as character set. Sorry if I might have misunderstood the question.

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1075209

The line

var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');

...is susceptible to single quotes in the resulting JSON (and other things; you'd have to double-escape lots of stuff). But you don't need or want to do that. Do this:

var json = <?php print json_encode(json_encode($rows)); ?>;

json_encode returns valid JSON, and JSON is a subset of JavaScript object initializer syntax, and so the above will result in valid JavaScript code describing the object. If you're outputting JavaScript code, as you appear to be from that line, there's no reason to go indirectly through a string. And as you've found, there's a reason not to.

Upvotes: 2

Related Questions