如何在yii2动作方法中向外部URL发送请求

时间:2016-09-23 11:55:34

标签: php json yii2

我有一个用php yii2框架编写的网站。 我有第二个用mvc.net编写,它有一个api,例如叫www.secondone.com/api/get_records。这个api返回json,我想在我的yii2应用程序操作中使用这个json。 在yii2操作中获取外部URL内容的方法是什么?

1 个答案:

答案 0 :(得分:2)

你可以尝试卷曲

  

CURL是一个允许您在PHP中发出HTTP请求的库。一切   您需要了解它(以及大多数其他扩展)可以找到   PHP手册。

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or
     

高。在PHP 4.2.3中,您将需要libcurl版本7.9.0或更高版本。   从PHP 4.3.0开始,您将需要一个7.9.8或7.9的libcurl版本   更高。 PHP 5.0.0需要libcurl版本7.10.5或更高版本。

     

虽然需要,但您也可以在没有cURL的情况下发出HTTP请求   在php.ini文件中启用allow_url_fopen。

这里有一些代码示例

$service_url = 'http://path/to/api.asmx/function_name';
$curl = curl_init($service_url);
$curl_post_data = array(
        'param1' => 'val1',
        'param2' => 'val2'  
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
    die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
相关问题