php curl post json [英] php curl post json

查看:178
本文介绍了php curl post json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现如果我尝试一个PHP POST卷曲,postvars发送正常。一旦我添加了内容类型的httpheader: application / json postvars不会再跨越。我已经尝试过postvars作为JSON字符串和查询字符串。



帮助?



**显示一些代码**

  $ ch = curl_init(); 

$ post = json_encode(array('p1'=>'blahblahblah','p2'=> json_encode(array(4,5,6))));

$ arr = array();
array_push($ arr,'Content-Type:application / json; charset = utf-8');

curl_setopt($ ch,CURLOPT_HTTPHEADER,$ arr);
curl_setopt($ ch,CURLOPT_URL,'https://domain.com/file.php');
curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_POSTFIELDS,$ post);

curl_exec($ ch);
curl_close($ ch);


解决方案

真正的HTTP Post, PHP自动化必须使用name = value对格式化,在PHP中最好的方法是使用http_build_query函数。



http://ca2.php.net/manual/en/function.http-build-query.php p>

有一个在PHP手册中使用curl的示例:



http://ca2.php.net/manual/en/function.curl-exec.php#98628 p>

您正在做的是一个RAW帖子,请参阅此其他问题:



如何使用curl将JSON发布到PHP



获取RAW Json数据的快速代码段。

 <?php 

print_r(json_decode(file_get_contents('php:// input')));


I've found that if I try a PHP POST curl, the postvars are sent fine. Once I add the httpheader of content-type: application/json the postvars don't go across anymore. I've tried the postvars as a JSON string and as a query string.

help?

** Showing some code **

$ch = curl_init();

$post =  json_encode(array('p1' => 'blahblahblah', 'p2' => json_encode(array(4,5,6))));

$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');

curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL, 'https://domain.com/file.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

curl_exec($ch);
curl_close($ch);

解决方案

A real HTTP Post, that gets broken into an array automagically by PHP must be formatted in name=value pairs, the best way to do this in PHP is using the http_build_query function.

http://ca2.php.net/manual/en/function.http-build-query.php

There is an example that works in the PHP Manual using curl:

http://ca2.php.net/manual/en/function.curl-exec.php#98628

What you're doing is a 'RAW' post, see this other question:

How to post JSON to PHP with curl

A quick snippet to get the RAW Json data.

<?php

print_r(json_decode(file_get_contents('php://input')));

这篇关于php curl post json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆