user3327714
user3327714

Reputation: 37

Insert HTML codes to specific location

I know this topic was posted everywhere, but their question is not I want. I want to insert some HTML codes before the page is loaded without touching the original code in the page.

Suppose my header was rendered by a function called render_header():

function render_body() {
return "<body>
    <div class='container'>
    <div class='a'>A</div>
    <div class='b'>B</div>
    </div>
    </body>";
}

From now, I want to insert HTML codes using PHP without editing the render_body(). I want a function that insert some divs to container'div.

render_body();
<?php *//Insert '<div class="c" inside div container* ?>

Upvotes: 0

Views: 265

Answers (2)

Michael Coxon
Michael Coxon

Reputation: 5520

The only thing I can think of is to turn on output buffering and then use the DOMDocument class to read in the entire buffer and then make changes to it. It is worth doing some reading of the documentation (http://www.php.net/manual/en/book.dom.php) provided in the script...

ie.:

<?php


function render_body() {
return "<body>
    <div class='container'>
    <div class='a'>A</div>
    <div class='b'>B</div>
    </div>
    </body>";
}  

$dom = new DOMDocument();

$dom->loadHTML(render_body());

// get body tag
$body = $dom->getElementsByTagName('body')->item(0);

// add a new element at the end of the body
$element = $dom->createElement('div', 'My new element at the end!');
$body->appendChild($element);

echo $dom->saveHTML(); // echo what is in the dom

?>

EDIT:

As per CD001's suggestions, I have tested this code and it works.

Upvotes: 1

CD001
CD001

Reputation: 8482

Just as an alternative using XPath - this should load in the output from render_body() to an XML (DOMDocument) object and create an XPath object to query your HTML so you can easily work out where you want to insert the new HTML.

This will probably only work if you're using XML well formed HTML though.

//read in the document
$xml = new DOMDocument();
$xml->loadHTML(render_body());

//create an XPath query object
$xpath = new DOMXpath($xml);

//create the HTML nodes you want to insert
// using $xml->createElement() ...

//find the node to which you want to attach the new content
$xmlDivClassA = $xpath->query('//body/div[@class="a"]')->item(0);
$xmlDivClassA->appendChild( /* the HTML nodes you've previously created */ );

//output
echo $xml->saveHTML();

Took a little while as I had to refer to the documentation ... too much JQuery lately it's ruining my ability to manipulate the DOM without looking things up :\

Upvotes: 1

Related Questions