php - 通过curl以指定格式发送数据?

标签 php node.js curl

我有以下函数在 php 和 nodejs 之间进行通信:

function toNode($data){

    //$data is array
    //$data example
    //$data = array("one"=>"yes","two"=>"no","three"=>array("yet"=>"another"))

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:'.$socket_port.'/posts');

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);

    curl_setopt($ch, CURLOPT_POST, true);

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_exec($ch);

    $feedback = curl_getinfo($ch);

}

以下是 Nodejs console.log 接收数据的方式:

 { one: 'yes',
 two: 'no',
'three[0][yet][0]':'another'}         //<---

这是我希望数据如何显示在nodejs端:

{ one: 'yes',
two: 'no',
three: [ { yet: 'another' } ] }       //<---

我到底怎样才能用curl实现这一点?我尝试过在接收信息的nodejs端使用此功能

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

但是失败了,如果我没记错的话,什么也没有输出。另外,进一步用于处理数据的函数在来自 php curl 或 native Nodejs 中的函数(未进行 url 编码)之间共享因此,最好是在 php 端解决问题...有人可以帮我吗?非常感谢...

编辑:包括解析nodejs端的信息:

app.post('/posts', function(req, res){

   if(req.headers.host == '127.0.0.1:'+socket_port) {
        if(req.method == 'POST') {
            var form = new formidable.IncomingForm();
            form.parse(req, function(err, fields, files) {

                res.writeHead(200, [[ "Content-Type", "text/plain"]
                        , ["Content-Length", 0]
                        ]);
                res.write('');
                res.end();

                furtherFunction(fields);                
            });
        }
    }

});

最佳答案

据我了解,您想要发送 json 数据。我这里没有看到任何json数据。我用谷歌搜索了一下。这里send-json-post-using-php ,我找到了如何在 php 中发送 json 数据。希望它会有所帮助。

关于php - 通过curl以指定格式发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021817/

相关文章:

php高效读取文件并插入sql

php - opencart编辑download.php报错

javascript - 如何逐行读取并仅返回数字大于 0.0 的行

mysql - Sequelize/mysql 在创建或更新数据时使用 100% CPU

node.js - 如何写入多行多列的csv

node.js - 如何在 Express 中编写一个函数,该函数在作为 API 调用时可以返回 JSON,但也可以在不使用 Axios/Fetch 的情况下在内部调用?

facebook - 如何在 Facebook 页面上发帖?

php - 使用 Symfony,我可以检查页面加载时打开和关闭的数据库连接数吗?

PHP file_get_contents 很慢并返回 500 Internal Server Error

java - 如何将 Java 日期格式的日期传递给 cURL (PHP)?