Yii2 控制台从外部服务器获取数据
Yii2 console fetch data from an external server
我正在创建一个控制台应用程序,我想在命令为 运行
时从另一个 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
可以检索到数据。
if allow_url_fopen is activated on your server you can use 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();
}
}
我正在创建一个控制台应用程序,我想在命令为 运行
时从另一个 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
可以检索到数据。
if allow_url_fopen is activated on your server you can use 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();
}
}