Parsing Python list with PHP - php

is there any way to parse Python list in PHP?
I have data coming from python stored in mysql, something like this:
[{u'hello: u'world'}]
And need to use it in PHP script. The data is a valid JSON, only difference are those leading u'
So I can replace all u' with ' and then replace all ' with " to get it into json.
When I replace everything, if there is ' in the actual value, it is replaced by " as well and brakes the json.
So.. I tried a lot of stuff, but none of them was able to parse proper json thus my question -> Is there any way to parse Python generated list/json-like data in PHP? I dont mind using some third-party library or etc, just want to get the data parsed...
Thank you

If you have access to python, you can convert it to json from the command line.
Here's an example.
$ echo "{u'key': u'value'}" |\
python -c "import sys, json, ast; print(json.dumps(ast.literal_eval(sys.stdin.read())))"
{"key": "value"}
Here's a better formatted version of the python oneliner:
import sys, json, ast
data = ast.literal_eval(sys.stdin.read())
print(json.dumps(data))
By using ast.literal_eval instead of regular eval we can evaluate the python dictionary literal and not worry about potential code execution vulnerabilities.

Related

Need help outtping json with python

Im in need of help outputting the json key with python. I tried to output the name "carl".
Python code :
from json import loads
import json,urllib2
class yomamma:
def __init__(self):
url = urlopen('http://localhost/name.php').read()
name = loads(url)
print "Hello" (name)
Php code (for the json which i made):
<?php
$arr = array('person_one'=>"Carl", 'person_two'=>"jack");
echo json_encode($arr);
the output of the php is :
{"person_one":"Carl","person_two":"jack"}
I'll just assume the PHP code works correctly, I don't know PHP very well.
On the client, I recommend using requests (installable through pip install requests):
import requests
r = requests.get('http://localhost/name.php')
data = r.json()
print data['person_one']
The .json method returns a Python dictionary.
Taking a closer look at your code, it seems you're trying to concatenate two strings by just writing them next to eachother. Instead, use either the concatenation operator (+):
print "Hello" + data['person_one']
Alternatively, you can use the string formatting functionality:
print "Hello {}".format(data['person_one'])
Or even fancier (but maybe a bit complex to understand for the start):
r = requests.get('http://localhost/name.php')
print "Hello {person_one}".format(**r.json())
try this:
import json
person_data = json.loads(url)
print "Hello {}".format(person_data["person_one"])

How to filter user' s input ( html, with PHP backend) with python?

There is a web application written in PHP and HTML. What I want is to filter a users input for a variety of cases and sanitize it. For example, I want to compare the input from a form (string) with a list of allowed strings and depending if it is right or wrong to trigger the suitable PHP function to handle this.
My question is how to bind the user input with the python script and then the outcome of this python script as an input for PHP?
thanks
You can call the Python script from your PHP file as a shell command, passing it JSON-formatted arguments. Then have the Python script output the response (also JSON encoded) and have the PHP file capture that. Here's an example I used recently, cobbled together from the links below:
PHP file:
$py_input = ... // Your data goes here.
// Call the Python script, passing it the JSON argument, and capturing the result.
$py_output = shell_exec('python script.py ' . escapeshellarg(json_encode($py_input)));
$py_result = json_decode($py_output);
Python file:
import json
php_input = json.loads(sys.argv[1]) # The first command line argument.
# Do your thing.
php_output = ... # Whatever your output is.
print json.dumps(php_output) # Print it out in JSON format.
Passing a Python list to php
executing Python script in PHP and exchanging data between the two

php `exec` calls python script. how return strings from python?

I use exec function calling python script from PHP script. Python writes to standard output two strings which I need in PHP script. The problem is that in these strings could be end of line characters \n ( so formally there are many lines in output), and according to exec manual array $output will contain
each line in it. What is elegant way to escape \n characters so that $output will contain only two string I want and no post processing of these two string needed?
EDIT: I can change python script.
Print the output in an easily parsable format, such as JSON, and parse it from PHP. For example, instead of:
print foo
print bar
Use something like:
import json
print json.dumps([foo, bar])
You read the JSON output form PHP and decode it using json_decode($output) into the desired array.
There really is nothing you can do about this outside of changing the way the python script outputs.
It is really easy to clean the returned data though.
exec('yourcommand', $array);
array_walk($array, function($value, $key) {
return trim($value);
});

Inline PHP (command line)

I would like to make something like tryruby.org. I take a line from the user (e.g., echo __FILE__) and I want to execute it in PHP and return the output back to the client.
I tried to do exec('php -r ' . $command, $output), but $output always contains the PHP help section.
How can I implement this feature?
To make php -r you have to have to put the code you want to execute between ' .. your code .. '
Example:
php -r ' $var = 34; print_r($var); '
It looks like your problem is that you aren't wrapping your code to be executed with ' '. You also need to be wary of ' in the code, special characters, escape sequences, etc.
In fact, if you insist on using exec(), it might be better to do this (to completely avoid having to worry about escaping and the such):
$command = base64_encode($command);
exec("php -r 'eval(base64_decode(\"$command\"));'", $output);
You could use eval() instead of what you're posting above.
The main issue here (both with eval() and your exec() code) is that taking PHP code from user input simply isn't safe:
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
Suggestion
Since you want to return the result of the PHP code, you could potentially do something cool with Ajax, where you pass the PHP code to a script (Base64 encoded, perhaps) as a parameter:
$code = base64_decode($_GET['code']);
// Clean the user input here
eval($code);
Ajax example using jQuery:
// assuming `code` contains the PHP code
var encoded = base64_enc(code);
$.get('execute.php?code=' + encoded, function(data) {
var result = new String(data);
// do something with the result here, such as displaying it
}, dataType='text');
For Base64 encoding in JavaScript, see this.
http://tryruby.org seems have an interactive Ruby shell. That seems to be a good starting point.
Here are two projects that provide such a shell for PHP: php_repl and phpsh.
The other part is the web interface for the interactive shell. For that part, I suggest you have a look at repl.it, which provides this service for many languages (but sadly not PHP). Here's a link to it's source code.
With this combination, you should be able to complete cour project.
Look up 'eval()' and more importantly, why eval() and what you're trying to do is very difficult to achieve in a secure manner. Imaging for example the user who inputs:
echo file_get_contents('/etc/passwd');
You'll need quite a bit of work to make this secure, including watching and filtering all system calls being made from the eval'd process.
Cheers

Extract data from HTML in PHP or Python

I need to extract this data and display a simple graph out of it.
Something like Equity Share Capital -> array (30.36, 17, 17 .... etc) would help.
<html:tr>
<html:td>Equity Share Capital</html:td>
<html:td class="numericalColumn">30.36</html:td>
<html:td class="numericalColumn">17.17</html:td>
<html:td class="numericalColumn">15.22</html:td>
<html:td class="numericalColumn">9.82</html:td>
<html:td class="numericalColumn">9.82</html:td>
</html:tr>
How do I go about this task in PHP or Python?
A good place to start looking would be the python module BeautifulSoup which extracts the text and places it into a table.
Assuming you've loaded the data into a variable called raw:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(raw)
for x in soup.findAll("html:td"):
if x.string == "Equity share capital":
VALS = [y.string for y in x.parent.findAll() if y.has_key("class")]
print VALS
This gives:
[u'30.36', u'17.17', u'15.22', u'9.82', u'9.82']
Which you'll note is a list of unicode strings, make sure to convert them to whatever type you desire before processing.
There are many ways to do this via BeautifulSoup. The nice thing I've found however is the quick hack is often good enough (TM) to get the job done!
BeautifulSoup
Don't forget lxml in Python. It also works well to extract data. It's harder to install but faster. http://pypi.python.org/pypi/lxml/2.2.8

Categories