我正在创建一个控制台应用程序,我想在命令运行时从另一个URL获取数据
这就是我实现控制台控制器的方法
<?php
namespace console\controllers;
use yii\helpers\Console;
use yii\console\Controller;
... other use imports
use Yii;
class UserController extends Controller
{
public function actionInit()
{
$urltofetchdata = "https://urltofetchjsondata"; //i expect to return json
$datas= //how do i get the data here so that i can proceedby
foreach($datas as $data){
$user = new User();
$user->name = $data->name;
$user->email = $data->email;
$user->save();
}
}
}
以便用户输入:
./yii user/init
可以检索数据。
答案 0 :(得分:1)
如果您的服务器上激活了allow_url_fopen,您可以使用file_get_contents远程获取数据;像这样的东西,
public function actionInit()
{
$urltofetchdata = "https://urltofetchjsondata"; //i expect to return json
$datas = json_decode(file_get_contents($urltofetchdata));
foreach($datas as $data) {
$user = new User();
$user->name = $data->name;
$user->email = $data->email;
$user->save();
}
}
如果您的服务器上禁用了allow_url_fopen
,则可以使用cURL
public function actionInit()
{
$urltofetchdata = "https://urltofetchjsondata"; //i expect to return json
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $urltofetchdata);
$result = curl_exec($ch);
curl_close($ch);
$datas = json_decode($result);
foreach($datas as $data) {
$user = new User();
$user->name = $data->name;
$user->email = $data->email;
$user->save();
}
}