I've got a php script which generates HTML content. Is there a way to send back that HTML content through JSON to my webpage from the php script?
Yes, you can use json_encode to take your HTML string and escape it as necessary to be valid JSON (it'll also do things that are unnecessary, sadly, unless you use flags to prevent it). For instance, if your original string is:
<p class="special">content</p>
...json_encode will produce this:
"<p class=\"special\">content<\/p>"
You'll notice it has an unnecessary backslash before the / near the end. You can use the JSON_UNESCAPED_SLASHES flag to prevent the unnecessary backslashes. json_encode(theString, JSON_UNESCAPED_SLASHES); produces:
"<p class=\"special\">content</p>"
Do Like this
1st put all your HTML content to array, then do json_encode
$html_content="<p>hello this is sample text";
$json_array=array(
'content'=>50,
'html_content'=>$html_content
);
echo json_encode($json_array);
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);
In PHP:
$data = "<html>....";
exit(json_encode($data));
Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/
You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.
Just to expand on #T.J. Crowder's answer.
json_encode does well with simple html strings, in my experience however json_encode often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.
All these answers didn't work for me.
But this one did:
json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);
Thanks to this answer.
Related
I have an API which sends data to a javascript which then throws the response into some input fields.
I wonder if I need to use htmlspecialchars on the json_encode? Like so:
json_encode(
array(
'some_text' => htmlspecialchars('Some special & characters'),
'maybe_html' => htmlspecialchars('some <b>html</b>'),
'etc' => htmlspecialchars('yo')
)
);
Certainly not. HTML entities make no difference or sense within JSON, and if the result is processed by Javascript and inserted into the document via the DOM API via appropriate methods, then escaping is not needed there either. Escaping should be done when data comes in contact with a specific output medium. Here the data must be correctly encoded as JSON (which json_encode does), HTML is nowhere to be found here. If anything, HTML escaping should be done in Javascript because it's closer to the HTML, but again, it's unnecessary since Javascript interacts with the DOM API and not HTML.
See The Great Escapism (Or: What You Need To Know To Work With Text Within Text)
Depends on what you're doing with the string data.
What is important is the correct header for the content type.
header('Content-type: application/json');
i need to remove () backslash in my string when using echo json_encode()?
my example..
$song_url = 116e9155e0afc11555cf33dc9c9bd25d.mp3
$resmsg[] = array("Song_name"=>"$song_name","Song_URL"=>"http://www.kbmusique.com/songs/$song_url");
echo json_encode($resmsg);
my output is
[{"Song_name":"djigh araouioui","Song_URL":"http:\/\/www.kbmusique.com\/songs\/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
but i need as
[{"Song_name":"djigh araouioui","Song_URL":"http://www.kbmusique.com/songs/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
Is there a way to solve this? Thank you.
Your comment indicates that you just need to get a copy/pastable URL for testing.
Just parse the JSON and extract the piece of data you need from it. i.e. If you want a text representation of something, then convert the JSON to text, don't try to hack the JSON into a specific form.
You could do this in PHP with json_decode, in a browser with JSON.parse(), or just use a tool such as the Chrome JSONView extension.
So a PHP file returns a string ( to an ajax call ) like this :
$output = $sessID."###".$sessEmail."###".$sessFirstName."###".$sessLanguage."###".$sessRememberMe;
and in javascript i do :
if (reply.indexOf("###") >= 0) {
arrayReply = reply.split("###");
user.ID = arrayReply[0];
user.Email = arrayReply[1];
user.FirstName = arrayReply[2];
user.Language = arrayReply[3];
user.RememberMe = arrayReply[4];
}
a problem can arise when parts of reply contain the the delimiter i use "###". What can I do in such a situation? Making the delimiter more complex/rare is not a solution in my opinion.
PS: I did try JSON but it's WAY SLOWER server side.
FINAL EDIT:
server side JSON is slower, and the same for client side, however it's not going to be a bottleneck ( 430ms for 100.000 calls ) and plus there is no need as Jules said below to re-invent the wheel. There was one more solution: bin2hex() in php [which reduced the time from 430ms to 240] and then get back the string in javascript with a hex2string function, however not worth the effort. JSON it is. Thank you all!
If as you say encoding as JSON is slower than you could try the following,
$output = '"' . some_kind_of_escape_function($sessID).'","'.some_kind_of_escape_function($sessEmail).'","'.some_kind_of_escape_function($sessFirstName).'","'.some_kind_of_escape_function($sessLanguage).'","'.$sessRememberMe.'"';
and of course replace some_kind_of_escape_function with the appropriate php function (e.g. addslashes or mysql_real_escape_string) it has been a while since I've done PHP development so choose the one that best suits your needs
Then it's a simple case of splitting by the comma and removing the quotes
One option is to use JSON object instead.
For PHP (using json_encode):
$output = json_encode(array(
"sessid" => $sessID,
"sessEmail" => $sessEmail,
"sessFirstName" => $sessFirstName,
"sessLanguage" => $sessLanguage,
"sessRememberMe" => $sessRememberMe
));
For JS (using jQuery method):
$.getJSON("/path/to/script.php", function(reply) {
user.ID = reply.sessid;
user.Email = reply.sessEmail;
user.FirstName = reply.sessFirstName;
user.Language = reply.sessLanguage;
user.RememberMe = reply.sessRememberMe;
});
Otherwise, you can use any other delimiter that possibly won't be found in the fields (or you can replace it throughout the fields). One of the examples is to use symbol of newline (\n).
Why develop your own format if there is already one?
use Json:
$output = json_encode(array('sessionID'=>$sessID,'sessionEmail'=>sessEmail,'sessionFirstName'=>$sessFirstName,'sessLanguage'=>$sessLanguage,'sessRememberMe'=>$sessRememberMe));
And for the Javsascript Side see
http://www.javascriptkit.com/dhtmltutors/ajaxgetpost4.shtml
or if your using JQuery etc. your Framework is much likely to have some kind of inbuild functionality such as http://api.jquery.com/jQuery.getJSON/
However if you want to use your ###-Delimiter i'd suggest you reduce it to just "#", for the sake of simplicity and space. After that introduce what is called an escape charater such as "\" So in a prepass you'll parse your input and replace all occurences of # with #, vice versa in the output. You can then Split your String using a special Regex, which only splits by # and not by "#"
You can use json.
http://php.net/manual/en/function.json-encode.php
How to JSON decode array elements in JavaScript?
i have a case where i have to send an html code from client side to server side through json object ,but there are some problems caused by symbols inside the html tag such as ",/ ...etc which create errors in the json object. I tried many ways to build the json but none of them were correct .I hop you understand my case clearly .
this is an example of my json structure:
{
"html":"the html code injected dynamical here"
}
as i said my main problem is that i am having problems caused by html symbols how can i solve it! please give me an explicit example on how to solve this problem and pars the html code successfully to json object.
I'm not sure about how you're building the JSON objects but if you're using json_encode() and json_decode() you shouldn't have any problems with HTML characters, they'll be escaped properly.
Not sure If I misread the question, but to pass json from server to client, use json_encode()
http://php.net/manual/en/function.json-encode.php
This should work for you and take care of all the escaping.
<?php
header('Content-type: application/json');
$json = array(
'html' => '<h1 style="color:#0F0">Hello World!</h1>'
);
echo json_encode($json);
exit;
Hmm, just learned this tidbit from reading the docs:
json_encode() won't work with
character sets other than UTF-8
I can't see why you'd need to send json to the server, maybe you can share the reason with us or someone can enlighten me in the comments?
Perhaps you could use url encoding.
You can encode the html. Some html encoding and decode can be find here:
http://code.google.com/p/jsool/source/browse/jsool-site/js/util/Encoder.js?r=176
You just need the html.encode and html.decode functions, that way you can do something like
function html_encode(string){
return string.replace(/./g,function(chr, index){
return chr.match(/[\w\d]/) ? chr : "&#"+chr.charCodeAt(0)+";" ;
});
},
function html_decode(string){
return string.replace(/&#[0-9]+;/g,function(text,index){
return String.fromCharCode(text.match(/[0-9]+/)[0]);
});
}
That way you can do
var html = html_encode(myhtml);
{"html": html}
to encode and recover the values using html_decode().
PS.: Sry, i didnt tested out the html_encode and decode functions, but its easy to find some at google.
If you are using jQuery this js library might help. http://www.rahulsingla.com/blog/2010/05/jquery-encode-decode-arbitrary-objects-to-and-from-json
In your javascript before you send the request do this:
var thing = {plugin: 'jquery-json', other: "blah-blah"};
var encoded = $.JSON.encode(thing);
Then after you send the request to php, do this to decode:
var thing = json_decode($_POST['thing']);
You can read more on this here
Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php