【问题标题】:How to get response using cURL in PHP如何在 PHP 中使用 cURL 获得响应
【发布时间】:2011-06-29 07:05:08
【问题描述】:

我想要一个独立的 PHP 类,我想要一个通过 cURL 调用 API 并获取响应的函数。有人可以帮助我吗?

谢谢。

【问题讨论】:

标签: php curl


【解决方案1】:

只需使用以下代码从restful web service url获取响应,我使用社交提及url。

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

【讨论】:

  • Oldie bug a goodie... +1 使用 curl_setopt_array()。比一遍又一遍地调用 curl_setopt() 干净得多。
  • 可以使用$ch = curl_init(); 然后在$options 中包含CURLOPT_URL =&gt; $url, 还是有问题,因为假设选项不一定按正确的顺序加载?
  • @s3c 调用curl_init()后设置URL就可以了。我刚刚测试了它。只有当您调用 curl_exec() 时才会处理这些选项。
【解决方案2】:

解决办法的关键是设置

CURLOPT_RETURNTRANSFER => true

然后

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER 告诉 PHP 将响应存储在变量中而不是将其打印到页面上,因此 $response 将包含您的响应。这是您最基本的工作代码(我认为,没有测试过):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

【讨论】:

    【解决方案3】:

    如果其他人遇到此问题,我将添加另一个答案以提供响应代码或“响应”中可能需要的其他信息。

    http://php.net/manual/en/function.curl-getinfo.php

    // init curl object        
    $ch = curl_init();
    
    // define options
    $optArray = array(
        CURLOPT_URL => 'http://www.google.com',
        CURLOPT_RETURNTRANSFER => true
    );
    
    // apply those options
    curl_setopt_array($ch, $optArray);
    
    // execute request and get response
    $result = curl_exec($ch);
    
    // also get the error and response code
    $errors = curl_error($ch);
    $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);
    
    var_dump($errors);
    var_dump($response);
    

    输出:

    string(0) ""
    int(200)
    
    // change www.google.com to www.googlebofus.co
    string(42) "Could not resolve host: www.googlebofus.co"
    int(0)
    

    【讨论】:

      【解决方案4】:

      终极curl php函数:

      function getURL($url,$fields=null,$method=null,$file=null){
          // author   = Ighor Toth <igtoth@gmail.com>
          // required:
          //      url     = include http or https 
          // optionals:
          //      fields  = must be array (e.g.: 'field1' => $field1, ...)
          //      method  = "GET", "POST"
          //      file    = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
          // please crete 'cookies' dir to store local cookies if neeeded
      
          // do not modify below
          $useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
          $timeout= 240;
          $dir = dirname(__FILE__);
          $_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
          $cookie_file    = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
          $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    
          curl_setopt($ch, CURLOPT_FAILONERROR, true);
          curl_setopt($ch, CURLOPT_HEADER, 0);
          curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
          curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
          curl_setopt($ch, CURLOPT_ENCODING, "" );
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
          curl_setopt($ch, CURLOPT_AUTOREFERER, true );
          curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
          curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
          curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
          if($file!=null){
              if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
                      die("curl setopt bit the dust: " . curl_error($ch));
              }
              //curl_setopt($ch, CURLOPT_FILE, $file);
              $timeout= 3600;
          }
          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
          curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
          if($fields!=null){
              $postvars = http_build_query($fields); // build the urlencoded data
              if($method=="POST"){
                  // set the url, number of POST vars, POST data
                  curl_setopt($ch, CURLOPT_POST, count($fields));
                  curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
              }
              if($method=="GET"){
                  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
                  $url = $url.'?'.$postvars;
              }
          }
          curl_setopt($ch, CURLOPT_URL, $url);
          $content = curl_exec($ch);
          if (!$content){
              $error = curl_error($ch);
              $info = curl_getinfo($ch);
              die("cURL request failed, error = {$error}; info = " . print_r($info, true));
          }
          if(curl_errno($ch)){
              echo 'error:' . curl_error($ch);
          } else {
              return $content;        
          }
          curl_close($ch);
      }
      

      【讨论】:

        【解决方案5】:

        我正在使用这个简单的

        '''' 类连接 {

        public $url;
        public $path;
        public $username;
        public $password;
        
            $ch = curl_init();
        
            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
            curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
        
            //PROPFIND request that lists all requested properties.
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
            $response = curl_exec($ch);
        
            curl_close($ch);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-29
          • 2018-02-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-12
          • 2018-09-26
          • 2019-10-24
          • 2021-06-30
          相关资源
          最近更新 更多