将PHP和HTML分开


Keep PHP and HTML separated

我的网站通过调用API打印用户位置。假设我在我的网站上的一个文件index.php中有以下代码:

<?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>

不过,我需要将PHP脚本和标记分开。我无法将PHP脚本嵌入到script元素中。我能做些什么来拥有一个PHP和一个HTML文件?

EDIT:使用include_once()而不是include,因为可以使用相对路径。

您可以将PHP移到其他文件中,然后将其include_once移回主文件中。

HTML文件仍然必须是.php文件,但为了更好的可维护性/可读性,您可以将所有PHP脚本(除了include之外)包含在不同的文件中。

例如:

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>

您还可以使用php框架,如Laravel、CodeIgniter或CakePHP这样您就可以将php逻辑与html代码分离,然后将数据发送到html页面。这对你未来的职业生涯是很好的练习。

您可以将PHP脚本放在一个单独的PHP文件中,并使用AJAX对其进行调用,然后使用Javascript打印PHP脚本生成的JSON数据。