H
H
hulktoster2020-06-17 18:31:21
React
hulktoster, 2020-06-17 18:31:21

What would such a React code look like in php?

I am writing a website on one CMS which is built on php. I don't know php myself, as I'm a front-end developer. And I write in js (React.js). Considering that I wrote the site on the CMS, I managed to make the entire site simply by pressing the buttons in the admin panel of the CMS itself. But you need to make a small php file that will display the weather of a particular city on the page. More precisely, only three fields and values. I get the values ​​using the API :

http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=32ae008b1c7259324aa50450687fabf5&units=metric


The essence of the task is to display this on the page:
City: London
Temparuture: 22.05
Pressure: 1012


And the API itself (not counting the fields I don’t need) looks like this:
{"main":{"temp":22.05,"pressure":1012},
"name":"London"}

Wrote React.js code that displays the weather:

class App extends React.Component {
  state = {
    city: "",
    temp: "",
    pressure: ""
  }    
      
  componentDidMount() {
    this.fetchData();
  }

  fetchData = async () => {
    const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=32ae008b1c7259324aa50450687fabf5&units=metric`);
    const data = await response.json();
    this.setState({
      city: data.name,
      temp: data.main.temp,
      pressure: data.main.pressure
    });
  };
        
  render() {
    return (
      <div className="App">
        City:{this.state.city}
        Temparuture:{this.state.temp}
        Pressure:{this.state.pressure}
      </div>
    );
   }
  }


Unfortunately, there is very little time until the moment when I have to show the work done and php cannot be learned "quickly". Perhaps there are developers here who know both PHP and React.js, and can help me with something.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-06-17
@hulktoster

<?php
function getWeather($city)
{
    $jsn = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q='.$city.',uk&appid=32ae008b1c7259324aa50450687fabf5&units=metric');
    $jsn = json_decode($jsn);
    
    echo $jsn->main->temp; // Выводит температуру
    echo '<br>'; // Перевод строки
    echo $jsn->main->pressure; // Выводит pressure
    echo '<br>'; // Перевод строки
    echo $city; // Выводит город
    
}

// Вызов функции: 
getWeather('London');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question