Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add HTML elements to the current page using PHP

Tags:

html

dom

php

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.

like image 555
user1462495 Avatar asked Oct 16 '25 07:10

user1462495


1 Answers

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>
like image 156
jchook Avatar answered Oct 17 '25 20:10

jchook