The mobile app developers wants an api to get a list of articles from our Drupal site. It should have these fields in the output:
- nid
- title
- field_teaser_body
The api resonse has to be in JSON format.
The field type of field_teaser_body
field is Long text
and text processing is Plain text
.
I created a custom code to get this working. Here's a simplified version of it.
$query = db_select('node', 'n');
$query
->fields('n', array('nid', 'title'))
->condition('n.status', 1)
->orderBy('n.created', 'DESC')
$result = $query->execute();
$nodes = array();
foreach ($result as $value) {
$node = node_load($value->nid);
$data = array(
'nid' => $node->nid,
'title' => $node->title,
'field_teaser_body' => !empty($node->field_teaser_body['und'][0]['value']) ? check_plain($node->field_teaser_body['und'][0]['value']) : '',
);
$data = (object) $data;
array_push($nodes, $data);
}
$content = new stdClass();
$content->nodes = $nodes;
print json_encode($content);
Just for the security purpose, I'm using check_plain()
function to sanitize the teaser body text. But, when using this function, it encodes all special characters.
For e.g.,
Bob's height is > than Alice.
converts to
Bob's height is > than Alice.
The mobile app developers said that they don't want any encoded text in the JSON output.
Is it a safe practice to send the unencoded (unsanitized) text in the JSON output ?
drupal_json_encode
thanjson_encode
.