本文实例讲述了php基于curl发送json格式字符串的方法。分享给大家供大家参考,具体如下:
/*
* post 发送json 格式数据
* @param $url string url
* @param $data_string string 请求的具体内容
* @return array
* code 状态码
* result 返回结果
*/
function post_json_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, curlopt_post, 1);
curl_setopt($ch, curlopt_url, $url);
curl_setopt($ch, curlopt_postfields, $data_string);
curl_setopt($ch, curlopt_httpheader, array(
'content-type: application/json; charset=utf-8',
'content-length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, curlinfo_http_code);
return array('code'=>$return_code, 'result'=>$return_content);
}
$arr = array('a'=>'555','b'=>56454564);
dump(post_json_data('http://192.168.211.1/html/dump.php',json_encode($arr)));
注意:接收数据的时候不是用 $_post,而是
$content = file_get_contents('php://input');
ps:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线json代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
json在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线xml/json互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
c语言风格/html/css/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
更多关于php相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《php网络编程技巧总结》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》、《php数据结构与算法教程》、《php程序设计算法总结》、《php运算与运算符用法总结》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!