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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With