如何以JSON格式向POST数据发送请求

时间:2017-06-14 09:34:32

标签: php json

我有一个Api端点来处理代码

<?php

    $name= $_POST['name'];
    $email = $_POST['email'];
    $password= $_POST['password'];
    $gender= $_POST['gender'];

    $con = mysqli_connect("localhost", "root", "qwerty", "db");
    $query= mysqli_query($con, "INSERT INTO users(name,email, password, gender) VALUES('$name','$email', '$password', '$gender')");

    if($query){
        echo "You are sucessfully Registered";
    }

    else{
        echo "your details could not be registered";
    }

    mysqli_close($con);

?>

如何使请求看起来像

{ 
   "name":"abc", 
   "email":"gmail", 
   "gender":"male" 
} 

我是php Api开发的新手

2 个答案:

答案 0 :(得分:2)

你必须像这样构建一个数组:

$data = array(
    'name' => $_POST['name'],
    'email' => $_POST['email'],
    'password' => $_POST['password']
);

然后你必须编码它:$encoded = json_encode($data)

答案 1 :(得分:1)

$data = array(
    'userID'      => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    'itemKind'    => 0,
    'value'       => 1,
    'description' => 'Boa saudaÁ„o.',
    'itemID'      => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);

$json = json_encode($data);

$client = new Zend_Http_Client($uri);
$client->setRawData($json, 'application/json')->request('POST');

使用此方法,您可以在帖子中发送请求