Imran Omar Bukhsh
Imran Omar Bukhsh

Reputation: 8071

Do i need to apply htmlspecialchars / htmlentites on json array?

I wanted to ask that in a php script of mine which I am accessing through an ajax request, I am returning json data ( converted from an array ) as such

 echo json_encode($row_array);

I get this data in jquery and display it in a form. Do i need to apply htmlspecialchars / htmlentites before returning the data?

Is do then whats the correct way to do it? The following code gives me an error:

echo htmlentities(json_encode($row_array));

Thanking you Imran

Upvotes: 2

Views: 7284

Answers (3)

Mitch McCoy
Mitch McCoy

Reputation: 1

I just had a problem with single quotes in a JSON array. Chrome doesn't like single quotes in a JSON response returned via ajax. I escaped each value with htmlspecialchars(, ENT_QUOTES).

$theoptions['MemberList'] = array();
while($row = mssql_fetch_assoc($result)) {
   $memberelement = array(
                       'Display'=> htmlspecialchars($row['FullName'], ENT_QUOTES),
                       'Value'      =>  $row['ID']);
   $theoptions['MemberList'][] = $memberelement;
}

header('Content-Type: application/json');
echo json_encode($theoptions);

Upvotes: 0

No Results Found
No Results Found

Reputation: 102834

Context is important.

You don't need to escape the data at all on the server side if it's going into a form input's value if you are using jQuery's val() function to populate it.

Example: http://jsfiddle.net/Y6TWv/1/

var data = '<strong>STRONG TEXT</strong>';

$('input').val(data); // output is escaped
$('p').text(data);    // output is escaped
$('p').html(data);   ​ // output is not escaped

In addition, if you were to escape the data, don't do it like this:

// escapes the entire json string, not good - quotes will be broken
echo htmlentities(json_encode($row_array));

You would have to escape each item of $row_array first before json encoding it, either with array_map after the array is built, or as you're building the array.

In general, you should prefer htmlspecialchars over htmlentities, but it's not likely you need either one.

Upvotes: 2

Ray
Ray

Reputation: 41478

Do not apply htmlentities in this way. You should walk the array before json encoding it and escape each element, then json encode the array of safe-to-display values. In your usage json is just a transport layer for the array. You are not displaying the json array, just the element data. Don't escape transport layers--it could make the json string invalid.

Upvotes: 2

Related Questions