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

yipeiwu_com5年前PHP代码库

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

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

<?php
header("Content-type:application/json;charset=utf-8");
$url="http://192.168.10.234:8080/uc/login/loginid";
$param=array(
  //注册字段
  "name"=>"test001",
  "pass"=>"xxxx",
);
$data = json_encode($param);
list($return_code, $return_content) = http_post_data($url, $data);//return_code是http状态码
print_r($return_content);exit;
function http_post_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($return_code, $return_content);
}

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中json格式数据操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP数组相加操作及与array_merge的区别浅析

发现问题 今天看到一段代码,是这么写的,感觉不熟悉,下面粘贴出来看看: <?php $array_one = [ 内容 ]; $array_two = [ 内容 ];...

讲解WordPress开发中一些常用的debug技巧

讲解WordPress开发中一些常用的debug技巧

在开发过程中,调试代码是非常重要的工作,而掌握一些 WordPress 的调试技巧,可以更好的进行调试。比如,在本地开发环境,你可能需要把全部的代码警告信息全部输出出来,方便修改代码不合...

php 操作excel文件的方法小结

一、php,不用COM,生成excel文件 复制代码 代码如下: <? header("Content-type:application/vnd.ms-excel"); heade...

PHP中SERIALIZE和JSON的序列化与反序列化操作区别分析

本文实例讲述了PHP中SERIALIZE和JSON的序列化与反序列化操作区别。分享给大家供大家参考,具体如下: PHP中SERIALIZE和JSON序列化与反序列化区别是什么呢,对于这个...

php读取文件内容至字符串中,同时去除换行、空行、行首行尾空格(Zjmainstay原创)

复制代码 代码如下: <?php  /*   *读取文件内容至字符串中,同时去除换行、行首行尾空格。   */ header("Content-type: text/html; c...