PHP取不同类型POST数据

POST常见四种类型Content-Type

  1. application/x-www-form-urlencoded浏览器原生表单的格式
  2. multipart/form-data 传文件用到的格式
  3. application/json json格式
  4. text/xml xml格式

php如何接收传参

前面两种常规方式从超全局变量$_POST,$_FILE中就能取到,不细说;

application/json

通过application/json类型传过来的数据我们需要使用另一种方法获取。

$post_data = file_get_contents("php://input");
$params = json_decode($post_data);

即从php输入流中获得全部post参数,然后解析成数组。

text/xml

处理xml格式也无法从$_POST直接获取,用如下方法:

$file_in = file_get_contents("php://input"); //接收post数据
$xml = simplexml_load_string($file_in);//转换post数据为simplexml对象

$data = array();
foreach($xml->children() as $child){
  $data[$child->getName()] = $child->__toString();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。