Reputation: 9419
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?
Upvotes: 10
Views: 16962
Reputation: 2025
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.
Upvotes: 3
Reputation: 17351
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>
Upvotes: 16
Reputation: 486
You can put the PHP script in a separated PHP file, and use AJAX to call it, then you use the Javascript to print the JSON data that generated by the PHP script.
Upvotes: 2