0
我有一個網站已經寫在php yii2框架。 我有第二個是寫在mvc.net有一個API例如www.secondone.com/api/get_records
。這個api返回json,我想在我的yii2應用程序操作中使用這個json
。 在yii2動作中獲取外部網址內容的方式是什麼?如何發送請求到yii2操作方法的外部url
我有一個網站已經寫在php yii2框架。 我有第二個是寫在mvc.net有一個API例如www.secondone.com/api/get_records
。這個api返回json,我想在我的yii2應用程序操作中使用這個json
。 在yii2動作中獲取外部網址內容的方式是什麼?如何發送請求到yii2操作方法的外部url
你可以嘗試捲曲
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開始,您需要一個libcurl版本,它的版本更高,爲7.9.8或 。 PHP 5.0.0需要libcurl版本7.10.5或更高版本。
你也可以不用cURL發出HTTP請求,雖然它需要 allow_url_fopen在你的php.ini文件中被啓用。
這裏的一些代碼示例
$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);
看看這個http://www.yiiframework.com/extension/yii2-curl/ –