2

I'm trying to return some code snippets from php to jquery. Everything works ok, but when I try to return html with <body> and <html> tags then I get my javascript code in output (raw code)

this is my code:

$snippetData['snippetId'][] = $snippetId;
$snippetData['title'][] = $title;
$snippetData['description'][] = $description;
$snippetData['snippet'][] = $code;
echo json_encode($snippetData);

EDIT:

To make it more clear this is what I store in this array:

snippedId = 5 (integer value)
title = 'some title'  (string value)
description 'some description' (string value)
snippet = '<html> <body> <title>some title </title> </body> </html>' (string value)
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
Alen
  • 897
  • 2
  • 15
  • 33

2 Answers2

6

Try this:

<?php echo json_encode($snippetData, JSON_HEX_QUOT | JSON_HEX_TAG);

Source

jdp
  • 3,446
  • 2
  • 30
  • 54
  • This escapes html, but when I try to decode it in jquery I get this (this wierd code is generated in place where normally should be head tag): http://pastebin.com/05K1yx3w – Alen Jan 10 '14 at 22:28
1

seems something is wrong with " char. try escaping them or base64 encode on html in json,

after getting data you can decode it.

ie you'll have:

JzxodG1sPiA8Ym9keT4gPHRpdGxlPnNvbWUgdGl0bGUgPC90aXRsZT4gPC9ib2R5PiA8L2h0bWw+Jw==

instead of

'<html> <body> <title>some title </title> </body> </html>'

when you decode, you'll get your snippet back

alpera
  • 509
  • 4
  • 9