Search code examples
phphtmljquerydomhtmlelements

Move tags/elements in dom with PHP


I have a problem, I'm coding my own helper class in php, but I want to move tags/elements in the DOM (document), for example, I want to move link tag in head and js to bottom in body...

(to do like $("link").appendTo("head").remove(); in jquery)

How can I proceed? I know exists an DOMDocument API in PHP, If it's possible to do with it, I would like an example.

Thanks for help.

(sorry for my bad english, i'm french...)


Solution

  • I created a library that allows you to crawl HTML5 and XML documents just like you do with jQuery.

    You can find it here.

    It should allow you to do exactly what you want!

    Example use:

    namespace PowerTools;
    
    // Get file content
    $htmlcode = file_get_contents( 'https://github.com' );
    
    // Define your DOMCrawler based on file string
    $H = new DOM_Query( $htmlcode );
    
    // Define your DOMCrawler based on an existing DOM_Query instance
    $H = new DOM_Query( $H->select('body') );
    
    // Passing a string (CSS selector)
    $s = $H->select( 'div.foo' );
    
    // Passing an element object (DOM Element)
    $s = $H->select( $documentBody );
    
    // Passing a DOM Query object
    $s = $H->select( $H->select('p + p') );
    
    // Select the body tag
    $body = $H->select('body');
    
    // Combine different classes as one selector to get all site blocks
    $siteblocks = $body->select('.site-header, .masthead, .site-body, .site-footer');
    
    // Nest your methods just like you would with jQuery
    $siteblocks->select('button')->add('span')->addClass('icon icon-printer');
    
    // Use a lambda function to set the text of all site blocks
    $siteblocks->text(function( $i, $val) {
        return $i . " - " . $val->attr('class');
    });
    
    // Append the following HTML to all site blocks
    $siteblocks->append('<div class="site-center"></div>');
    
    // Use a descendant selector to select the site's footer
    $sitefooter = $body->select('.site-footer > .site-center');
    
    // Set some attributes for the site's footer
    $sitefooter->attr(array('id' => 'aweeesome', 'data-val' => 'see'));
    
    // Use a lambda function to set the attributes of all site blocks
    $siteblocks->attr('data-val', function( $i, $val) {
        return $i . " - " . $val->attr('class') . " - photo by Kelly Clark";
    });
    
    // Select the parent of the site's footer
    $sitefooterparent = $sitefooter->parent();
    
    // Remove the class of all i-tags within the site's footer's parent
    $sitefooterparent->select('i')->removeAttr('class');
    
    // Wrap the site's footer within two nex selectors
    $sitefooter->wrap('<section><div class="footer-wrapper"></div></section>');
    
    [...]
    

    Supported methods :
    1. Renamed 'select', for obvious reasons
    2. Renamed 'void', since 'empty' is a reserved word in PHP