【问题标题】:Posting a JSON object to a REST API using PHP使用 PHP 将 JSON 对象发布到 REST API
【发布时间】:2015-10-14 02:22:20
【问题描述】:

我在 stackoverflow 上找到了一些有用的链接,但它们并没有帮助我完成我的任务,因为我是一个尝试编写 PHP 或使用 curl 等的初学者。

Send json post using php

Posting JSON data to API using CURL

我一直在 Chrome 中使用 Postman 来测试 API 调用,但现在我想在我的 Apache Web 服务器上组装一个演示系统。

有没有人有 PHP webform 发布到 json 对象到 REST API 的示例?

这是我要发送的示例:

<?php
$url = "https://api.url/api/v1//accounts/create";
$jdata = json_encode($data);
$data = [{
  "status": "active",
  "username": ["uname"],
  "password": ["pword"],
  "attributes": {
    "forenames": ["fname"],
    "surname": ["lname"],
    "emailAddress": ["email"]
                 },
          }]
?>

任何建议都会很棒。就像我说的,我是 curl 和 php 的新手,不熟悉其他文章中提到的数组方法,并且 ["info"] 元素应该使用我的网络表单中填写的信息来填充。

我希望我的表述简洁明了,但如果您需要更多信息,请告诉我。

斯诺克

【问题讨论】:

    标签: php json api rest curl


    【解决方案1】:

    尝试以下类似的方法,相应地修改步骤 1 和 2:

    function sendRequest($data,$url)
    {
        $postdata = http_build_query(array('data'=>$data));
        $opts = array('http' =>
          array(
              'method'  => 'POST',
              'header'  => "Content-type: application/x-www-form-urlencoded \r\n",
                           //"X-Requested-With: XMLHttpRequest \r\n".
                           //"curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)\r\n",
              'content' => $postdata,
              'ignore_errors' => true,
              'timeout' =>  10,
          )
        );
        $context  = stream_context_create($opts);
        return file_get_contents($url, false, $context);
    }
    
    
    // 1.- add your json
    $data = '[{
        "status"      : "active",
        "username"    : ["uname"],
        "password"    : ["pword"],
        "attributes"  : {
            "forenames"   : ["fname"],
            "surname"     : ["lname"],
            "emailAddress": ["email"]
        },
    }]';
    
    // 2.- add api endpoint
    $url= "https://api.url/api/v1//accounts/create"; 
    
    // 3.- fire
    $result = sendRequest($data,$url);
    
    // 4.- dump result
    echo $result;
    die();
    

    祝你好运!

    【讨论】:

    • 能否给一个完整的json post示例
    猜你喜欢
    • 2016-02-10
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多