PHP code example of lspbupt / yii2-curl

1. Go to this page and download the library: Download lspbupt/yii2-curl library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lspbupt / yii2-curl example snippets


return [
    'components' => [
        'baiduApi' => [
            'class' => 'lspbupt\curl\CurlHttp',
            'host' => 'apis.baidu.com',
            'beforeRequest' => function($params, $curlHttp) {
                //you need put you baidu api key here
                $apikey = 'xxxxxx';
                $curlHttp->setHeader('apikey', $apikey);
                return $params;
            },
            'afterRequest' => function($response, $curlHttp) {
                // you may want process the request here, this is just a example
                $code = curl_getinfo($curlHttp->getCurl(), CURLINFO_HTTP_CODE);
                if($code == 200) {
                    $data = json_decode($response, true);
                    if(empty($data) || empty($data['code'])) {
                        Yii::warning("error!", "curl.baidu");
                    }
                    Yii::info("ok!", "curl.baidu");
                    return $response;
                }
                Yii::error("error", "curl.baidu");
                return $response;
            }
            //'protocol' => 'http',
            //'port' => 80,
            // ...
        ],
    ],   
    // ....
];

// you can use this search beijin weather,  http://apistore.baidu.com/apiworks/servicedetail/112.html
$data = Yii::$app->baiduApi
                ->setGet()
                ->httpExec("/apistore/weatherservice/recentweathers", ['cityname' => '北京', 'cityid' => '101010100']);
// you can also use this search the real address of a ip address, http://apistore.baidu.com/apiworks/servicedetail/114.html
$data = Yii::$app->baiduApi
            ->setGet()
            ->httpExec("/apistore/iplookupservice/iplookup", ['ip' => '117.89.35.58']);
// any other apis

    $data = Yii::$app->baiduApi->setDebug()->httpExec("/apistore/xxx", []);

    $data = Yii::$app->baiduApi
        ->setHeader('Content-Type', 'application/json;charset=utf-8')
        ->httpExec("/apistore/xxx", []);

return [
    // 其它配置
    'modules' => [
        // ...
        'curl' => ['class' => 'lspbupt\curl\module\Module'],
        'as foo' => ['class' => 'some_class_extends_BeforeActionBehavior']
        // ...
    ],
    // 其它配置
];

php composer.phar