Python的cPickle从PHP反序列化?
我需要在PHP中反序列化一个字典,这个字典是用Python中的cPickle序列化的。
在这种情况下,我可能可以直接用正则表达式提取我想要的信息,但有没有更好的方法呢?有没有什么PHP的扩展可以让我更自然地反序列化整个字典?
显然,它在Python中的序列化方式是这样的:
import cPickle as pickle
data = { 'user_id' : 5 }
pickled = pickle.dumps(data)
print pickled
这种序列化的内容不能轻易粘贴到这里,因为它包含二进制数据。
4 个回答
3
我知道这个问题已经很久了,但我最近在做一个Django 1.3的应用(大约是2012年的时候)时需要解决这个问题,找到了这个:
https://github.com/terryf/Phpickle
所以就留着这个链接,以防哪天其他人也需要同样的解决方案。
5
你能进行系统调用吗?你可以用下面这个Python脚本把pickle格式的数据转换成json格式:
# pickle2json.py
import sys, optparse, cPickle, os
try:
import json
except:
import simplejson as json
# Setup the arguments this script can accept from the command line
parser = optparse.OptionParser()
parser.add_option('-p','--pickled_data_path',dest="pickled_data_path",type="string",help="Path to the file containing pickled data.")
parser.add_option('-j','--json_data_path',dest="json_data_path",type="string",help="Path to where the json data should be saved.")
opts,args=parser.parse_args()
# Load in the pickled data from either a file or the standard input stream
if opts.pickled_data_path:
unpickled_data = cPickle.loads(open(opts.pickled_data_path).read())
else:
unpickled_data = cPickle.loads(sys.stdin.read())
# Output the json version of the data either to another file or to the standard output
if opts.json_data_path:
open(opts.json_data_path, 'w').write(json.dumps(unpickled_data))
else:
print json.dumps(unpickled_data)
这样,如果你是从文件中获取数据,可以这样做:
<?php
exec("python pickle2json.py -p pickled_data.txt", $json_data = array());
?>
或者如果你想把数据保存到文件中,可以这样做:
<?php
system("python pickle2json.py -p pickled_data.txt -j p_to_j.json");
?>
上面的代码可能不是很完美(我不是PHP开发者),但这样的方式对你有用吗?
6
如果你想在用不同编程语言写的程序之间共享数据对象,使用像JSON这样的方式来进行数据的序列化和反序列化可能会更简单。大多数主流编程语言都有支持JSON的库。