I am trying to convert a code in Php to Python, it consists of encoding a variable obtained with the chr function with base64 using the base64_encode function.
Here is the code in Php:
$data = chr(ord('a')+ord('b'));
$data = base64_encode($data);
echo $data;
result:
ww==
Here is what I tried to do in Python:
from base64 import b64encode
data = chr(ord('a')+ord('b'))
data = b64encode(data.encode()) // data.encode() is mandatory or I get an error saying that b64encode require a bytes-like object
print(data)
result:
b'w4M='
Thank you for your help
Aymeric
I don't know if it's the real answer to the question, but the problem is that python string from version 3 are in unicode. so the php-code can be replaced:
<?php
$data = chr(ord('a')+ord('b'));
$data = utf8_encode($data);
echo base64_encode($data); //w4M=
or you can use https://www.php.net/manual/en/function.mb-chr.php for this
so for changing python code to work it as php - you need to encode data in latin-1:
from base64 import b64encode
data = chr(ord('a')+ord('b')).encode('latin-1')
data = b64encode(data)
print(data) # b'ww=='
print(data.decode()) # ww==
Related
I have JSON that has been saved in a text box on my site to a database below.
{"#type":"GOOOGLE.COM","#id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"#id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}
I want to convert it to look properly in PHP as so:
{"#type":"GOOOGLE.COM","#id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"#id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}
I tried doing a json_encode but its not working. How do i convert that string with all those escape quotes etc to a normal json string in PHP?
I tried as so:
$str = "{"#type":"GOOOGLE.COM","#id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"#id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}"
$data = json_encode($str, true);
return $data;
You need to decode HTML entities back into characters:
https://www.php.net/manual/en/function.htmlspecialchars-decode.php
$json = htmlspecialchars_decode($str, true); // valid json string
$data = json_decode($json); // convert json to php data structure
return $data;
I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};
I am working with a translation API but here is an issue. I am using JSON in response and when I do json_encode of Hindi then the out is like "\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948"
My code is given below
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data); die;
and the response is
{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}
If you are running PHP 5.4 or greater, pass the JSON_UNESCAPED_UNICODEparameter when calling json_encode
Example:
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
This is correct json and when you display it in the browser and / or parse it, it will result in an object with the correct keys and values:
var json_string = '{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}',
json = JSON.parse(json_string);
// or directly:
var json2 = {"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"};
console.log(json_string);
console.log(json);
console.log(json2);
document.write(json_string);
document.write('<br>');
document.write(json.hindi);
document.write('<br>');
document.write(json2.hindi);
The reason for this is likely that these characters are not in UTF-8 (I could not find them, at least). From the PHP documentation on json_encode:
All string data must be UTF-8 encoded.
This means that it will have to convert it to a 'description' of the characters. Do not worry, if you decode it again it will very likely be correct.
I have a solution to this problem. It works fine for me.
$data = array();
$data['hindi'] = base64_encode('यह कार है');
$data['english'] = 'This is car';
$encoded_text=json_encode($data);
To retrieve the hindi part of data:
$hindi=base64_decode(json_decode($encoded_text)->hindi);
I have an encoded string (it is too long to be posted here). When I use different utilities for decoding the string (http://www.the-art-of-web.com/javascript/escape/) the string looks perfect after urldecode(). However, when I actually pass the string through urldecode() in my php file on my testing environment the first 100 or so characters are missing. I cannot figure out why. I have tried both urldecode and rawurldecode. If you want to see the string I am trying to process you can make a GET request against this url http://pacific-wave-7885.herokuapp.com/api/opencart the string I am working with is the "contents" value of the JSON object
What i am trying to accomplish:
I want to make a php file that calls the above api address, gets the contents from the JSON object, decodes the string and parses the code.
here is what I have tried:
function utf8_urldecode($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
return html_entity_decode($str,null,'UTF-8');;
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://pacific-wave-7885.herokuapp.com/api/opencart', false, $context);
$contents_decode = utf8_urldecode($file);
echo $contents_decode;
You can see with this code that the "contents" starts with "language->load('shipping/usps')" and is missing the first 100 or so characters of that part of the string.
I have also tried this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://pacific-wave-7885.herokuapp.com/api/opencart");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$data = json_decode($output, true);
$contents = $data[0]['contents'];
$contents_decode = urldecode($contents);
echo $contents_decode;
curl_close($ch);
This also produces the same result - part of the beginning of the string is missing.
to reiterate: if you grab the encoded string straight from the JSON object and use an online decoding tool the string looks great, but once it is passed through urldecode() in my php file the first part of the string is missing characters.
If anyone can see what I am missing I would be so grateful.
Just fyi: My php environment is the latest version of XAMPP with php5 and the JSON object is coming from a NODE server with express.js.
If anyone has a better idea of how I can pass php code as a string from a Node server to a PHP server and then parse it I would be open to that as well.
I'm going to make two assumptions:
It's showing up starting at language->load('shipping/usps');
You are viewing the returned string in your browser.
Good news is that you aren't missing any characters! The browser is simply misinterpreting the tags -
<?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this->
The browser is trying to make sense of it - it doesn't know this is PHP, it thinks it is HTML. It sees < and thinks "oh cool, beginning of an HTML tag." And then it sees ? and it just tries to figure out what kind of malformed tag this is, and then it see's -> and it decides it must be an HTML comment, so it parses it as:
<!--?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this--->
Change echo $contents_decode; to echo "<textarea>" . $contents_decode . "</textarea>" and you'll see the full string.
Why not just return the data (instead of a PHP block in the contents) and have your PHP class on the receiving end decode the JSON and complete the logic.
If you are insisting on getting the PHP block back...it might be easier to just return a JSON response from node/express and use json_decode to pull it into an array. In playing with this the only way I could make your PHP block JSON friendly was to escape it then encodeURIComponent.
<?php
$jsonString = '{
"name":"usps.php",
"version":1,
"platform":"opencart",
"contents":"%253C%253Fphp%250Aclass%2520ModelShippingUsps%2520extends...57D%250A%2509%2509%257D%250A%250A%2509%2509return%2520%2524method_data%253B%250A%2509%257D%250A%257D%250A%253F%253E",
"_id":"53c40942bddf820200000007",
"__v":0
}
';
$jsonArr = json_decode( $jsonString, true);
var_dump( urldecode( urldecode( $jsonArr["contents"] ) ) );
?>
I'm trying to create a rest service for my android application where an external database returns items to be stored in the applications local database. I've got everything working except blobs are being returned as null.
this is an example of my jason response.(picture and thumbnail fields are blobs)
{"id":"2","user_id":"1","name":"testing","type":"bouldering","picture":null,"lat":"36","long":"81","alt":"41932","accuracy":"53","thumbnail":null}
Here is my php script to return the data.
<?php
require_once('config.php');
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$sql = 'select * from spot_main';
$results =$mysqli->query($sql);
$spots = array(); //array to parse jason from
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
echo json_encode($spots);
?>
Anyone know of a solution to this problem? I know I'm not doing this the most efficient way(better to store images in the filesystem), but I need this to work.
Encode the binary data as base64 before you generate the JSON.
$obj->picture = base64_encode($binaryData);
You can then decode this in your Android application with any base 64 decoder. Since API level 8 there is a built in util class. Otherwise there are plenty of external libs you can use for targetting Android 2.1 or earlier.
you have to make BLOB to base64_encode
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
Then prepare a foreach loop like this
foreach($spots as $key=>$value){
$newArrData[$key] = $spots[$key];
$newArrData[$key]['picture'] = base64_encode($spots[$key]['picture']);
$newArrData[$key]['thumbnail'] = base64_encode($spots[$key]['thumbnail']);
}
header('Content-type: application/json');
echo json_encode($newArrData);
It seems that json_encode works with UTF-8 encoded data only. You can use json_last_error() to detect json_encode error.