How to Send 2D array through php cURL

五迷三道 提交于 2019-12-27 00:39:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!