Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep PHP and HTML separated

Tags:

html

php

My website prints the user location by calling an API. Say I have the following code all in one file index.php on my website:

<?php
    $sIP = $_SERVER['REMOTE_ADDR'];
    $sURL = "http://ipinfo.io/" .$sIP . "/json";
    $sJSON = file_get_contents($sURL);
    $view = (object) array();
    $view->JSON = $sJSON;
?>

<!DOCTYPE html>
<html>
    <head>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
    <script>
        // global string of Data
        var gsData = <?= $view->JSON ?>

        $(document).ready(function(){
            var sRegion = gsData.region;
            $('#result').html(sRegion);
        });
    </script>
    <div>Region from data is:</div>
    <div id="result"></div>
</body>

Though, I need to keep the PHP script and the markup separated. I can't embed the PHP script in a script element. What can I do to have a PHP and a HTML file?

like image 248
Cesare Avatar asked Dec 31 '15 17:12

Cesare


2 Answers

EDIT: Use include_once() instead of include because you can use relative paths.

You can move the PHP into other files and then include_once it back into the main file.

The HTML file will still have to be a .php file, but you can include all of your PHP script (besides the include) in a different file for better maintainability / readability.

For example:

script.php

<?php
    $sIP = $_SERVER['REMOTE_ADDR'];
    $sURL = "http://ipinfo.io/" .$sIP . "/json";
    $sJSON = file_get_contents($sURL);
    $view = (object) array();
    $view->JSON = $sJSON;
?>

index.php

<?php include_once("script.php") ?>
<!-- ^ is the only PHP you will need to include a separate PHP file -->
<!DOCTYPE html>
<html>
    <head>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
    <script>
        // global string of Data
        var gsData = <?= $view->JSON ?>

        $(document).ready(function(){
            var sRegion = gsData.region;
            $('#result').html(sRegion);
        });
    </script>
    <div>Region from data is:</div>
    <div id="result"></div>
</body>
like image 153
Jonathan Lam Avatar answered Sep 30 '22 07:09

Jonathan Lam


You can also use php framework like Laravel, CodeIgniter or CakePHP, so that you can separate your php logic from html code and then send data to html page. It is very good practice for your future career.

like image 25
sabbir Avatar answered Sep 30 '22 07:09

sabbir