PHP基于curl模拟post提交json数据示例

本文实例讲述了PHP基于curl模拟post提交json数据。分享给大家供大家参考,具体如下:

这里php模拟post提交json数据操作的关键是在头部设置Content-Type:

  1. <?php
  2. header("Content-type:application/json;charset=utf-8");
  3. $url="http://192.168.10.234:8080/uc/login/loginid";
  4. $param=array(
  5. //注册字段
  6. "name"=>"test001",
  7. "pass"=>"xxxx",
  8. );
  9. $data = json_encode($param);
  10. list($return_code, $return_content) = http_post_data($url, $data);//return_code是http状态码
  11. print_r($return_content);exit;
  12. function http_post_data($url, $data_string) {
  13. $ch = curl_init();
  14. curl_setopt($ch, CURLOPT_POST, 1);
  15. curl_setopt($ch, CURLOPT_URL, $url);
  16. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  17. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  18. "Content-Type: application/json; charset=utf-8",
  19. "Content-Length: " . strlen($data_string))
  20. ); //phpfensi.com
  21. ob_start();
  22. curl_exec($ch);
  23. $return_content = ob_get_contents();
  24. ob_end_clean();
  25. $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  26. return array($return_code, $return_content);
  27. }