Estación Meteorológica Central de interfaz de tiempo] [laravel5.7 la primera interfaz laravel

Pasear por puestos de trabajo, no parece aprender laravel no hace un ~ ~

entorno PHP como no voy a mencionar -

cuerpo:

En primer lugar, descargar e instalar laravel

Tutorial Oficial: https://laravelacademy.org/laravel-docs-5_7

Instalación de la etapa de montaje se puede omitir

Mi gente perezosa, de un solo clic de descarga directa descomprimir el paquete y lo dejan: https://laravelacademy.org/resources-download

Se encontró extracción acabada falta archivo de configuración .env

.Env nuevo archivo en el directorio raíz del proyecto

//window cmd命令:
type nul >.env
//linux 命令:
touch .env

Abrir el Bloc de notas y entrar en la siguiente parada

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Xioiluh8yuYi/jljt2pS40ATuqpAFDuclTV9vf+uDgs=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

línea de comandos ejecute el siguiente comando de generación de claves raíz

 php artisan key:generate

Configurar el sitio en el directorio público

Abra el sitio para ver estas cosas, listo para obtener instrucciones

En segundo lugar, el nuevo controlador

Interesadas pueden dirigirse a los documentos oficiales mirar la estructura de directorios, no se interesa en lectura

Generar un comando de marcha recomendada, ejecute el controlador de tiempo Crear API módulo en el directorio raíz

php artisan make:controller Api/WeatherController

En este momento, la aplicación / HTTP / controladores / directorio de archivos Api generará WeatherController.php (comando veterano no puede crear directamente un nuevo controlador)

 

En tercer lugar, el nuevo método de control

Abrir WeatherController.php añadir método GetWeather en clase


class WeaghterController extends Controller
{
    function getWeather(){
        echo 'halo wo~';
    }
}

En cuarto lugar, configurar el enrutamiento

Está interesado puede ir a ver el documento oficial de configuración de enrutamiento en detalle, no interesa en lectura

rutas abiertas / web.php enrutamiento archivo de configuración, añadir una línea

//get请求 ‘/getWeather’ 指向 Api模块  WeatherController控制器 getWeather方法
Route::get('getWeather', 'Api\WeatherController@getWeather');

Dirija su navegador a http: // dominio / GetWeather, se puede ver el halo wo ~ ', sino que significa que los métodos de controlador y rutas para mejorar

En quinto lugar, subiendo tiempo Interfaz

Entra en la web oficial de la Central de Observatorio Meteorológico Tiempo  http://www.nmc.cn/

Consulta que desea un lugar como Shenzhen http://www.nmc.cn/publish/forecast/AGD/shenzhen.html

Abra su modo de depuración F12 navegador y luego actualice la página para encontrar el código correspondiente a Shenzhen, por ejemplo, donde 59 493

Ver red solicita netword

Copia la URL del enlace es conseguir  http://www.nmc.cn/f/rest/real/59493?_=1539152574236

Eso http: dominio / f / descansar / reales / número de la ciudad (hacia atrás parámetro _ = 1539152574236  fecha y hora actual), ha sido probado y el nombre de dominio puede cambiar, prestar atención a la interfaz de actualización

Beneficios: parámetro de retorno dentro del icono del tiempo weather.img, icono del sitio en: 

"http://image.nmc.cn/static2/site/nmc/themes/basic/weather/white/day/"+weather.img+".png"

Por ejemplo, aquí weather.img = 1, entonces el icono disponible en http://image.nmc.cn/static2/site/nmc/themes/basic/weather/white/day/1.png

En sexto lugar, escribir sus propias interfaces

El controlador cambia simplemente de Piedra


class WeatherController extends Controller
{
    /**
     * 封装一个get请求方法
     * @param $url 网址
     * @param null $_header 请求头
     * @return mixed
     */
    function get($url,$_header = NULL){
        //通过curl实现get请求 感兴趣的朋友百度 php curl深入了解
        $curl = curl_init();
        if( stripos($url, 'https://') !==FALSE )
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if ( $_header != NULL )
        {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $_header);
        }
        $ret    = curl_exec($curl);
        $info   = curl_getinfo($curl);
        curl_close($curl);
        return $ret;
    }

    /**
     * 天气查询接口(深圳)
     */
    function getWeather(){
        //中央气象局接口地址
        $url = 'http://www.nmc.cn/f/rest/real/59493?_='.time()*1000;
        //模拟请求
        $get_weather = $this->get($url);
        //格式化处理结果
        $get_weather = json_decode($get_weather,1);
        //拼装需要的数据
        $weather = [
            'city'  =>  empty($get_weather['station']['city'])?"":$get_weather['station']['city'],
            'weather'  =>  empty($get_weather['weather']['info'])?"":$get_weather['weather']['info'],
            'img_url'  =>  empty($get_weather['weather'])?"":"http://image.nmc.cn/static2/site/nmc/themes/basic/weather/white/day/".$get_weather['weather']['img'].".png",
            'direct'  =>  empty($get_weather['wind']['direct'])?"":$get_weather['wind']['direct'],
            'power'  =>  empty($get_weather['wind']['power'])?"":$get_weather['wind']['power'],
            'temperature'  =>  empty($get_weather['weather']['temperature'])?"":$get_weather['weather']['temperature'],
            'date' => date("Y-m-d",time())
        ];
        exit(json_encode($weather));
    }
}

retorno de interfaz de comprobación

 

Publicado 35 artículos originales · ganado elogios 18 · vistas 370 000 +

Supongo que te gusta

Origin blog.csdn.net/TXX_c/article/details/82995400
Recomendado
Clasificación