Yii2控制台从外部服务器获取数据
问题描述:
I am creating a console application where I would like to fetch data from another url whenever the command is run
This is how I have implemented the console controller
<?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();
}
}
}
so that when a user types:
./yii user/init
the data can be retrieved.
我正在创建一个控制台应用程序,我想在命令运行时从另一个URL获取数据 p >
这就是我实现控制台控制器的方法 p>
&lt;?php
命名空间控制台\控制器;
使用yii \ helpers \ console;
使用yii \ console \ Controller;
...其他使用导入
使用Yii;
class UserController扩展Controller
{
公共函数actionInit()
{\ n $ urltofetchdata =“https:// urltofetchjsondata”; //我希望返回json
$ datas = //如何在这里获取数据,以便我可以继续
foreach($ datas as $ data){
$ user = new User() ;
$ user-&gt; name = $ data-&gt; name;
$ user-&gt; email = $ data-&gt; email;
$ user-&gt; save();
} \ n}
}
code> pre>
以便用户输入: p>
./ yii user / init \ n code> pre>
可以检索数据。 p>
div>
答
if allow_url_fopen is activated on your server you can use file_get_contents to grab the data remotely; something like this,
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();
}
}
if allow_url_fopen
is disabled on your server, you can use 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();
}
}