All,
I make a JSON request to a web server using PHP and it returns me a JSON response in a variable. The JSON response will have lots of keys and values. The JSON response I get from the server has special characters in it. So, I use the following statement to convert it to UTF8,decode the JSON and use it as an array to display to the UI.
$response = json_decode(utf8_encode($jsonresponse));
Now, I have to pass the same value to the server in a JSON request to do some stuff. However, when I pass
$jsonrequest = json_encode(utf8_encode($request));
to the server, it fails.
The following code succeeds in reading special characters and displaying it to the UI. But fails if I have to pass the utf8_encode value to the server.
The current whole roundtrip code is as under:
$requestdata = json_encode($request);
$jsonresponse = //Do something to get from server;
$response = json_decode(utf8_encode($jsonresponse));
How can I modify it such that I pass the exact value as to what I receieved from the json response from the server?
The JSON response I get from the server has special characters in it. So, I use the following statement to convert it to UTF8,decode the JSON and use it as an array to display to the UI.
JSON data already comes encoded in UTF-8. You shouldn't convert it to UTF-8 again; you'll corrupt the data.
Instead of this:
$response = json_decode(utf8_encode($jsonresponse));
You should have this:
$response = json_decode($jsonresponse); //already UTF-8!
Set This into your php connection :
$sql = “SET NAMES ‘utf8′”;
mysql_query($sql, $link);
have you tryed switching the places of the functions?
$jsonrequest = utf8_encode(json_encode($request));
utf8_encode only encodes strings not arrays
You convert the initial request to UTF-8, so I assume it's something else. But when you send the data back, you do not convert it back to the original encoding.
Are you sure you send the data in the encoding expected by the server?
I also use both ZF and utf-8 encoded strings in AJAX calls and I think that the uft8_encode and utf8_decode functions should be obsolete.
Do you have a valid meta tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" / >
and a valid doctype
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
?
Related
I receive a token in this format :
{"signature": "MEQCIFf4uQXQYR6fA48cHZMwR5K0bO/wsK5ygoCukmAfWslIAiAdc4kN1BEixxrreSI3W3x4a92+fFTw7/Ulqw9RuJPRzg\u003d\u003d","protocolVersion": "ECv1", "signedMessage": "{\"encryptedMessage\":\"HKdqg8pDCiAwaHmGeI+/7xIDXXCTSfK+/SERLh94NBX6l99w7vNgBenMCiaAGvO+nbHkmnaOnwMcq/DpRhFtCJuYjAGKA83UePYjleSgXp8AjTKUweXxpqNEVvexSeflHBQNcx4stvB7lhsCeW9SMhecebfkcgQyGlawBECXrsIWhfIRGHklC6KE18tlA0GfvsQLhKreWspHCxQjgiBDim6uR57aKzTzlTFGYK+IB1mMJbVFTrEeBnKOAlvdt8Nh4BH3DhrmV3HVl+Ydc9V2G6iGZ6EmPxe3QG5dC9aYGollEXieasTFZm1Bt/LQMdyHmQEd+cmdIQNfGhxzz5pWpLP9g8LuoG+8h69TYaVFY2o0FjP2vSuPqGhMlXhcWgb/gJsiAOLGkS2ZdFbhpQg3kEyS5f/h91Wuoxy08JHpFxsvzWL3skfJ5eQc/BykvHyzzxzK\",\"ephemeralPublicKey\":\"BFnxpfpfIeFLmJ/KM/GcQyhU0MBlEReejnKa71gKFnV+5N2t3WNBnaaNu02gjy7Z5d07XO5+O77Qx3abHnw5rwk\\u003d\",\"tag\":\"kbnLkGZKyDKBWQAh6AyCNL55V4SF8DiZ4PeIudtKBH0\\u003d\"}"}
I need to json_decode it, do something with it then push it back. If I json_decode it, I will get the \u003d character decoded to =, which is fine. But how do I encode it back ? I think I played with every possible conversion function in PHP and I'm fresh out of ideas.
Here's a sandbox to play around with : http://sandbox.onlinephpfunctions.com/code/b93defec84a9a6f22f5085fbb7628b5afa816d95
In normal work you do not need to encode = to \u003d but if you must use somthing like this:
$encoded = str_replace('=','\\u003d', $encoded);
Note about your sandbox example:
In your example the token variable signedMessage is json in json
but after changes return as single json and not json in json like before changes.
maybe its fine for your application but check it
I have raw encoded base64 emails that I would like to decode. However on the raw email data, there is 3 sections to it.
The first section is HEADERS.
The second section is HTML content / tags.
The third section is the encoded base64.
I can manually add the string to my program and decode it just fine. However, I want to TARGET or PULL the encoded message into my program, so when I run it, its automatic.
But how do I target the encryption data when the header and html content / tags are in the way? I can read files through PHP, but would I do something like
if (strlength IS REALLY LONG == encoded data)
{decode that data}
Based on the following link, your solution would be something like this:
How to check whether the string is base64 encoded or not
$regex = '^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$';
if(preg_match($regex,$string) != false){
//some operation
$decoded = base64_decode($string);
}
I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.
I am using jQuery.parseJSON() to parse a response from jQuery.ajax() call to a PHP script.
The code works except on some server the characters 0000 are inserted at the start of the response string causing jQuery.parseJSON() to fail.
I can not figure how those character are being inserted, any ideas?
The characters are not in the PHP encoded string before echoing response.
Here is the scenario:
PHP script creates JSON string with:
$html = json_encode(myArrayOfValues);
echo $html
jQuery.ajax receives encoded string in:
....success: function(html, textStatus){
var response = jQuery.parseJSON(html);
....
To fixed the problem I added function that removes inserted characters and changed:
var response = jQuery.parseJSON(html);
to:
var response = parseJSONResponse(html);
Where:
function parseJSONResponse(html){
var foundChar = html.indexOf("{");
if(foundChar > 0 ){
html = html.substring(foundChar);
}
var response = jQuery.parseJSON(html);
return response;
}
Ultimately, it works but I'd like to know where the inserted characters are coming from and if there is a way to prevent them being inserted.
This could be a character encoding related issue. \u0000 is the NULL character. Although this could just be a coincidence it seems worth looking into.
I think the preferred character encoding for json is utf-8. Try adding this to the head of your calling page and see if it resolves the issue:
<meta charset="utf-8">
Hope that helps!
I have a problem creating an input validation hash. JavaScript submits data to API and API validates the sent data with json_encode. Basically it works like this:
$input=array('name'='John Doe','city'=>'New York');
$validationHash=sha1(json_encode($input).$key); // Key is known to both servers
If PHP connects to another server, then everything works. It also works through JavaScript (I have a custom sha1() function there as well):
var validationHash=sha1(JSON.stringify({'name':'John Doe','city'=>'New York'})+key);
My problem comes when the string contains UTF-8 characters. For example, if one of the values is:
Ränisipelgasöösel
Then PHP server that receives the command converts it to this after JSON encoding:
R\u00e4nisipelgas\u00f6\u00f6sel
I need to do this in JavaScript as well, but I haven't been able to work out how. I need to make sure that I send proper validation hash to the server or the command fails. I found from Google that unescape(encodeURIComponent(string)) and decodeURIComponent() could be used, but neither gives me the same string that PHP has and validates with.
UTF-8 is used on both client and server.
Any ideas?
It does not seem to be possible. The only working solution I have found is to encode all data with encodeURIComponent() on browser side and with rawurlencode() on PHP side and then calculate the JSON from these values in arrays.
My fix was to raw url encode my json data like so.
rawurlencode( json_encode( $data ) );
And then from within javascript decode the raw url encoded json and then parse the json string like so.
JSON.parse( decodeURIComponent( data ) );
Hope this helps.
Why not base64 encode the data for safe transport? It encodes UTF-8 characters in a safe string that can be sent across different mediums - php, javascript etc. That way you can base64 decode the string at the receiving end. Voila!
By base64 encoding the data, i mean base64 encoding the values and not the whole json string
is you html page encoding utf-8?
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">