初学者PHP:显示代码的函数中的Html?

时间:2014-03-25 17:27:37

标签: php html

目前正在阅读本书:

http://commons.oreilly.com/wiki/index.php/PHP_Cookbook/Forms

示例如下:

    <?php 
        if (isset($_POST['stage']) && ('process' == $_POST['stage'])) {
            process_form();
        } else {
            print_form();
        }

        function print_form() {
            echo <<<END
                <form action="$_SERVER[PHP_SELF]" method="post">
                What is your first name?
                <input type="text" name="first_name">
                <input type="hidden" name="stage" value="process">
                <input type="submit" value="Say Hello">
                </form>
        END;
        }

        function process_form() {
            echo 'Hello ' . $_POST['first_name'] . '!';
        } 
     ?>

但是......当您加载页面时,表单和按钮会显示,但它也会在

之后打印所有代码

所以......加载的页面正确显示了表单,但随后显示了文本:

END; }

            function process_form() {
                echo 'Hello ' . $_POST['first_name'] . '!';
            } 
         ?>

2 个答案:

答案 0 :(得分:1)

示例:

    $content = <<<EOL
        contentcontentcontentcontentcontentcontentcontentcontentcontent
EOL; // will end it

    $content = <<<EOL
        contentcontentcontentcontentcontentcontentcontentcontentcontent
    EOL; // will NOT end it

所以它需要在开始

答案 1 :(得分:0)

EOF只有当它的结束标记位于没有标签/其他字符的行上时才会关闭。

   <?php 
    if (isset($_POST['stage']) && ('process' == $_POST['stage'])) {
        process_form();
    } else {
        print_form();
    }

    function print_form() {
        echo <<<END
            <form action="$_SERVER[PHP_SELF]" method="post">
            What is your first name?
            <input type="text" name="first_name">
            <input type="hidden" name="stage" value="process">
            <input type="submit" value="Say Hello">
            </form>
END; // NOTE THIS, NO TABS BEFORE
    }

    function process_form() {
        echo 'Hello ' . $_POST['first_name'] . '!';
    } 
 ?>

如果我在你身边,我会这样做的:

        echo '<form action="$_SERVER[PHP_SELF]" method="post">
        What is your first name?
        <input type="text" name="first_name">
        <input type="hidden" name="stage" value="process">
        <input type="submit" value="Say Hello">
        </form>';

更整洁,更容易阅读。如果您需要将所有代码放在另一个循环中,该怎么办?你需要缩进每一行,并确保不要在END之前放置标签/空格;线。

如果另一个dev使用编辑器添加自动缩进编辑代码怎么办? : - )