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

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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失