Reputation: 2139
I have a web site which has written in php yii2 framework.
I have second one which is written in mvc.net which has an api for example called www.secondone.com/api/get_records
. This api returns json and I want to use this json
in my yii2 application action.
What is the way to get content of an external url in yii2 action?
Upvotes: 0
Views: 2470
Reputation: 1877
you can try curl
CURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.
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
higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file.
here's some code sample
$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);
Upvotes: 3