问题
I'm working with a a distributed system where a php app sends a post request to a python app.
My code is pretty straight forward:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
I have a 2d php array that looks like:
array(3) { [0]=> array(2) { ["a"]=> 'aaa' ["token"]=> string(55) "146bf00b2cb8709" } [1]=> array(2) { ["a"]=> string(52) "bbb" ["token"]=> string(55) "146bf00b2cb96e74302" } [2]=> array(2) { ["a"]=> string(52) "ccc" ["token"]=> string(55) "146bf00b2cb96e6c422417" } }
I want to transmit this via php curl, but I'm not sure how to do this in a way that is decodable on the other end in python.
回答1:
php
// 2d array
$arr = array(array(1,2,3),array(4,5,6),array(7,8,9));
// 2d array into json
$json = json_encode($arr) // [[1,2,3],[4,5,6],[7,8,9]]
send($json)
python
import json
r = request.body # receives request from php
json = json.loads(r)
print json[0] # [1,2,3]
回答2:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
Will encode your request as an HTTP query and transform your data into a multipart/form-data.
The python application must be an HTTP server and be able to receive this request. The decoding will be done by the HTTP framework/module.
来源:https://stackoverflow.com/questions/32335668/how-to-send-2d-array-through-php-curl