dounao1856 2017-06-11 07:34
浏览 47
已采纳

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.

  • 写回答

1条回答 默认 最新

  • douzhi1937 2017-06-11 11:44
    关注

    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();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))