PHP is a server side scripting language. You can't run it directly by just opening the PHP file into your browser because it needs an interpreter to be feed into and then you will get your desired output.
What you did in the command line was exactly how it's supposed to work. You fed your php code into the PHP interactive shell and then it executed the code using the interpreter accordingly and showed you the output.
As you have mentioned that you are using Ubuntu so in order to execute the code in a browser you need to install PHP along with an HTTP server like Apache or Nginx etc.
After installing both of them then you will start the HTTP server process and then you will create a file with .php extension under /var/www/html/ assuming you installed Apache HTTP Server.
When you do so you will be able to visit your file through the browser using the following link as:
http://localhost/index.php
You can execute the following commands to get a working server in Ubuntu:
sudo add-apt-repository ppa:ondrej/apache2
sudo apt-get update
sudo apt-get install apache2
sudo apt-get install php7.2
sudo service apache2 start
If you want to setup a VHOST which is recommended always, you can do so the following way:
Execute the command to create the VHOST config file:
sudo nano /etc/apache2/sites-available/project1.loc.conf
Then copy the following config and paste it in the file and save the conf file:
<VirtualHost *:80>
ServerName project1.loc
ServerAlias project1.loc
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/project1.loc
<Directory /var/www/html/project1.loc/>
Options All
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Next, enable the VHOST and restart apache:
sudo a2ensite project1.loc.conf
sudo systemctl restart apache2
Add the following line in your /etc/hosts as well:
127.0.0.1 project1.loc
Flush the DNS cache after each change in your hosts file:
sudo systemd-resolve --flush-cache
Next execute the following command to create the project directory:
sudo mkdir /var/www/html/project1.loc
Next, execute the following command to create your PHP file (where your code will reside):
touch /var/www/html/project1.loc/index.php
Then you can visit your file using the following link in the browser as:
http://project1.loc/index.php
Of course it will be blank at the beginning just edit /var/www/html/project1.loc/index.php to go further. Good luck!