PHP基于CURL发送JSON格式字符串的方法示例
author:一佰互联 2019-04-25   click:188

本文实例讲述了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程序设计有所帮助。