skip to Main Content

hi am working on a project where i want to swap 2 div elements by each other. I want to accomplish this by php. so the whole element with id 2 needs to come above element with div 1. is there a way to to that?

$html = '

<div id="row1">
<div class="test>
<h1>this text is from row 1</h1>
</div>
</div>
<div id="row2">
<p>this is from row 2</p>
</div>

result must be

<div id="row2">
<p>this is from row 2</p>
</div>

<div id="row1">
<div class="test>
<h1>this text is from row 1</h1>
</div>
</div>

I did not found a solution yet. I found a way to accomplish this by javascript. But i want to do this in php. i know it must be done by dome. But I am really new to php.

2

Answers


  1. PHP runs on the server side, it does not affect the HTML code on the browser side.

    If you want to display these 2 divs separately. So can you access them as two separate variables, e.g. $div1 and $div2?

    Then you could do it

    $result = $div2 + $div1;
    
    Login or Signup to reply.
  2. Just to give you a starting point: you could use a PHP library for the "DOM manipulation" like PHP DOM Wrapper or PHP Html Parser. Or you could you could use the PHP built-in DOMDocument class:

    <?php
    $html = '
    <div id="row1">
    <div class="test">
    <h1>this text is from row 1</h1>
    </div>
    </div>
    <div id="row2">
    <p>this is from row 2</p>
    </div>';
    
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    
    // do the DOM manipulation
    
    $html = $doc->saveHTML();
    // remove added characters by the DOMDocument
    $html = substr($html, strpos($html, "n") + 1); // remove first line 
    $html = substr($html, 12); // remove <html><body> from the beginning
    $html = substr($html, 0, strlen($html) - 14);  // remove </body></html> from the end
    
    echo $html;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search