首页 文章

如何在PHP中使用cURL获取响应

提问于
浏览
49

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

谢谢 .

3 回答

  • 15

    解决方案的关键是设定

    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);
    
  • 94

    如果有其他人遇到这个问题,我会添加另一个答案来提供响应代码或“响应”中可能需要的其他信息 .

    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)
    
  • 61

    只需使用下面的代码来获取来自restful web service 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;
    }
    

相关问题