How to get PHP to manipulate HTML code (copy/paste) before sending to the browser.
I want to use PHP to get html
code form inside h1
and paste it in h2
. On server. Before page is send over to the browser.
e.g ;
<h1> Some HTML CODE </h1>
<h2> <!-- EMPTY --> </h2>
<?php
// $var1 = HTML CODE from inside of h1
// Paste in $var1 inside h2
// Display The Page
?>
Edit: manipulating DOM before outputting through browser:
<?php
$my_html = '<div>
<h1>This is a h1</h1>
<h2>This is a h2</h2>
</div>';
$dom = new DOMDocument();
$dom->loadHTML($my_html);
$h1 = $dom->getElementsByTagName('h1')->item(0)->nodeValue;
var_dump($h1); // "This is a h1"
$dom->getElementsByTagName('h2')->item(0)->nodeValue = $h1;
echo $dom->saveHTML();
This is just an example. Read up on DOMDocument's documentation.
Previous answer: You can't. PHP runs on the server side and javascript (thereby jQuery) on the client side. PHP doesn't know how to handle anything happening in the browser after the page has loaded.
I think there's some kind of fundamental misunderstanding how PHP (and JS) works. PHP creates the HTML page, it doesn't know how the browser will render it and it can't go "back" to the already rendered page to make changes. (Yes, I know it's possible, but not the same way JavaScript on a browser would do it.)
If you want to avoid coding the same thing twice you can use variables or functions. For example to have the same text in both h1
and h2
:
$content = "Hello World!";
echo "<h1>$content</h1>";
echo "<h2>$content</h2>";
// output: <h1>Hello World!</h1><h2>Hello World!</h2>
But if you want the page to change after it's been sent to the browser you have to use JavaScript.