dongpao5658 2014-10-24 10:00
浏览 16
已采纳

PHP等效于以下CURL代码

I have a strange problem with PHP Curl. I want to set post fields option multiple times. What is the equivalent PHP code for the following CURL code:

curl -X POST https://example.com \
 -d 'contacts=my_list' \
 -d 'data[]={"email":"address1@domain.com","name":"contactName1"}' \
 -d 'data[]={"email":"address2@domain.com","name":"contactName2"}'

I want to send data[] as multiples of CURLOPT_POSTFIELDS. I already tried setting post field as

$post = "?contacts=my_list&data[]=%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D&data[]=%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D"

Can we have curl set CURLOPT_POSTFIELDS two times like

$post1 = "contacts=my_list&data[]=%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D";
$post2 = "data[]=%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D";
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post2);
curl_exec($this->ch);
  • 写回答

2条回答 默认 最新

  • dongyou4411 2014-10-24 10:31
    关注

    As mentioned in the comments, this is the code you are looking for:

    <?php
    $post1 = "contacts=my_list&data[]=%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D";
    $post2 = "data[]=%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D";
    curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post1 . '&' . $post2);
    curl_exec($this->ch);
    ?>
    

    But the best and clearest way to do it is to put all information in arrays and let http_build_query() do the job:

    <?php
      $c = curl_init();
      curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($c, CURLOPT_URL, 'http://your_url_here.com');
      curl_setopt($c, CURLOPT_MAXREDIRS, 10);
      curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
    
      $postData = array(
       'contacts' => 'my_list',
       'data' => array(
          array('email' => 'address1@domain.com', 'name' => 'contactName1'),
          array('email' => 'address2@domain.com', 'name' => 'contactName2'),
       ),
    );
      curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($postData));
      curl_exec($c);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)