【问题标题】:Posting JSON to URL using PHP curl使用 PHP curl 将 JSON 发布到 URL
【发布时间】:2011-02-23 21:23:44
【问题描述】:

我有以下 JSON 代码:

{"用户名":"user1","密码":"123456"}

我需要传递给一个 url,比如说:http://api.mywebsite.com

我是一个极端的 php 新手,所以我一直在关注 curl 教程,但这是我当前的 PHP 代码:

<?php

function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => true,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle compressed
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;

}

?>

【问题讨论】:

    标签: php json curl


    【解决方案1】:

    您可能需要查看 CURLOPT_POSTFIELDS 和 CURLOPT_POST 选项。这些允许您执行 POST 请求并将数据集传递到请求中的 CURLOPT_POSTFIELDS。

    以下内容:

    $body = 'bar=1&foo=2&baz=3';
    $c = curl_init ($url);
    curl_setopt ($c, CURLOPT_POST, true);
    curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
    curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
    

    【讨论】:

      【解决方案2】:

      当你想使用普通的 GET 参数时:

      $jsonString ='{"username":"user1","password":"123456"}';
      $params = json_decode($jsonString);
      
      $getParams = '';
      $first = true;
      foreach ($params as $key => $param){
          if ($first){
              $getParams .= '?';
              $first = false;
          } else{
              $getParams .= '&';
          }
      
          $getParams .= $key .'=' .$param;
      }
      
      echo $getParams;
      get_web_page($url . $getParams);
      

      【讨论】:

        猜你喜欢
        • 2010-10-23
        • 2011-12-19
        • 2020-12-09
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 2016-09-23
        相关资源
        最近更新 更多