Add HTML elements to the current page using PHP

14,697

Solution 1

You can open/close "blocks" of PHP wherever you like in your HTML

<div id="firstDiv">
    <?php echo '<div id="firstDivA"></div>'; ?>
</div>
<div id="secondDiv">
    <?php echo '<div id="secondDivA"></div>'; ?>
</div>

You can also capture the output if necessary with ob_start() and ob_get_clean():

<?php
$separator = "\n";

ob_start();
echo '<div id="firstDivA"></div>' . $separator;
echo '<div id="secondDivA"></div>' . $separator;
$content = ob_get_clean();

$sections = explode($separator, $content);
?>
<div id="firstDiv">
    <?php echo $sections[0]; ?>
</div>
<div id="secondDiv">
    <?php echo $sections[1]; ?>
</div>

Solution 2

The .php file is continuous thus if you have two separate <?php ?> tags they will be able to share the same variables.

 <div id="firstDiv">
 <?php
    echo "<div id=\"firstDivA\"></div>";
    $div2  = "<div id=\"secondDivA\"></div>";
 ?>
 </div>
 <div id="secondDiv">
    <?php echo $div2 ?>
 </div>

This will give the desired effect. (Demonstrates the use of variables)

Solution 3

Why not just move the relevant code to the right place?

<div id="firstDiv"> 
    <?php 
        echo "<div id=\"firstDivA\"></div>"; 
    ?> 
</div> 
<div id="secondDiv"> 
    <?php 
        echo "<div id=\"secondDivA\"></div>"; 
    ?> 
</div> 
Share:
14,697
user1462495
Author by

user1462495

Updated on June 04, 2022

Comments

  • user1462495
    user1462495 almost 2 years

    So I have the need to dynamically add html content using php which isnt the tricky part but I'm trying to put the HTML into a different location in the document than where the PHP is being run. So for example:

    <div id="firstDiv">
        <?php
            echo "<div id=\"firstDivA\"></div>";
            echo "<div id=\"secondDivA\"></div>";
        ?>
    </div>
    <div id="secondDiv">
    </div>
    

    But I want to be able to place the some HTML inside "secondDiv" using the PHP that is executed in the "firstDiv". The end result should be:

    <div id="firstDiv">
        <div id="firstDivA"></div>
    </div>
    <div id="secondDiv">
        <div id="secondDivA"></div>
    </div>
    

    But I have no idea how to go about doing that. I read about some of the DOM stuff in PHP 5 but I couldn't find anything about modifying the current document.

    • Cranio
      Cranio almost 12 years
      Why would you do that? What's the problem in moving the code inside the other DIV?