Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中使用JSON格式发送POST请求_Php_Json_Post - Fatal编程技术网

如何在PHP中使用JSON格式发送POST请求

如何在PHP中使用JSON格式发送POST请求,php,json,post,Php,Json,Post,我已经能够使用适用于chrome的高级Rest客户端扩展将POST查询发送到特定的URL和以下代码: 作为标题,我输入了以下内容: Accept: application/json version: 1.0.2 Authorization: code sadkj4-sadj-as22-asdk2 作为机构: { "email" : "$email", <====PHP variable passed as argument "password" : "$password

我已经能够使用适用于chrome的高级Rest客户端扩展将POST查询发送到特定的URL和以下代码:

作为标题,我输入了以下内容:

Accept: application/json
version: 1.0.2
Authorization: code sadkj4-sadj-as22-asdk2
作为机构:

{
   "email" : "$email",    <====PHP variable passed as argument
   "password" : "$password",  <====PHP variable passed as argument
   "UserVerified" : true, 
   "notificationOption" :
      [
         {
            "notificationType" : "NOTIFICATION1",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION2",
            "enabled" : false
         },
         {
            "notificationType" : "NOTIFICATION3",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION4",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION5",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION6",
            "enabled" : true
         }
      ],
    "cap":"uc",
    "GeneratedPassword":true
}
并将内容类型设置为:application/json

我成功地通过发送请求的URL获得了响应,但是现在我想创建一个PHP函数,它可以通过将$email和$password作为参数传递来实现这一点

我听到有人说我应该使用guzzle来完成这项任务,但我不知道怎么做,而且如果我不需要的话,我也不想使用第三方库。还有别的办法吗?
在此方面的任何帮助都将不胜感激。

您需要一个HTTP客户端库来与web服务器交互,guzzle就是其中之一,另一个例子是Zend\HTTP。如果不使用库,可能会很混乱,因为这样您就必须自己管理HTTP头、正文、url等

下一个最简单的方法是使用PHP curl库,核心方法是使用PHP套接字实现所有功能。

如果可能,使用curl。准备json数据,包括$json_字符串_数据中的电子邮件/密码


嗨,谢谢你的回复。我想知道在这个例子中你把主体放在哪里了?在这个例子中:curl\u setopt$ch,CURLOPT\u POSTFIELDS,$json\u string\u data;
$json_string_data = '{"email" : "' . $email . '", "password" : "' . $password . '", ...}';
$ch = curl_init('http://your_api_url');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'version: 1.0.2',
    'Authorization: code sadkj4-sadj-as22-asdk2',
    'Content-Length: ' . strlen($json_string_data))
);
$result = curl_exec($ch);