Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Dom Manipulations Laravel Package

24hoursmedia/php-dom-manipulations

Lightweight PHP helpers for manipulating HTML DOM documents. Create, find, update, replace, and remove nodes and attributes with a simple API suited for scraping, templating, and HTML cleanup tasks in legacy or modern PHP projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require 24hoursmedia/php-dom-manipulations
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "24HoursMedia\\DomManipulations\\": "vendor/24hoursmedia/php-dom-manipulations/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Load a DOMDocument and apply a manipulation:

    use DomManipulations\DomManipulations;
    
    $dom = new \DOMDocument();
    $dom->loadHTML('<div id="content"><p>Hello</p><p>World</p></div>');
    
    $manipulator = new DomManipulations($dom);
    $manipulator->removeElementsByTagName('p'); // Removes all `<p>` tags
    echo $dom->saveHTML();
    
  3. Key Entry Points:

    • DomManipulations class (main facade for DOM operations).
    • Methods like removeElementsByTagName(), addClass(), removeClass(), setAttribute(), etc.
    • Check the source code for full method list.

Implementation Patterns

Common Workflows

  1. Scraping & Cleaning HTML:

    $dom = new \DOMDocument();
    $dom->loadHTML($rawHtml);
    $manipulator = new DomManipulations($dom);
    
    // Remove unwanted elements (e.g., scripts, ads)
    $manipulator->removeElementsByTagName(['script', 'iframe', 'noscript']);
    
    // Normalize classes (e.g., add/remove prefixes)
    $manipulator->addClass('content *', 'normalized-class');
    
  2. Dynamic Attribute Manipulation:

    // Batch update attributes
    $manipulator->setAttribute('a[href]', 'target', '_blank');
    $manipulator->removeAttribute('div[data-tracking]', 'data-tracking');
    
    // Conditional logic (e.g., only update specific links)
    $links = $dom->getElementsByTagName('a');
    foreach ($links as $link) {
        if (strpos($link->getAttribute('href'), 'external.com') !== false) {
            $manipulator->addClass($link, 'external-link');
        }
    }
    
  3. Integration with Laravel:

    • Blade Templates: Use the package to pre-process HTML before rendering:
      $cleanedHtml = $manipulator->process($rawHtml);
      return view('template', ['content' => $cleanedHtml]);
      
    • Service Provider: Bind the manipulator for dependency injection:
      $this->app->bind(DomManipulations::class, function ($app) {
          $dom = new \DOMDocument();
          return new DomManipulations($dom);
      });
      
  4. Batch Processing:

    $dom = new \DOMDocument();
    $dom->loadHTML($html);
    
    $manipulator = new DomManipulations($dom);
    $manipulator->batch([
        'remove' => ['.old-class', '#legacy-id'],
        'add'    => ['.new-class', 'body', 'global-style'],
    ]);
    

Integration Tips

  • Leverage Laravel Collections: Convert DOM nodes to collections for easier manipulation:
    $nodes = collect($dom->getElementsByTagName('div'));
    $nodes->each(function ($node) {
        $manipulator->setAttribute($node, 'data-processed', 'true');
    });
    
  • Combine with SimpleHTMLDom: For complex scraping, use this package for post-processing:
    $html = file_get_html('https://example.com');
    $dom = new \DOMDocument();
    $dom->loadHTML($html->save());
    $manipulator = new DomManipulations($dom);
    // Clean up...
    

Gotchas and Tips

Pitfalls

  1. DOMDocument Quirks:

    • The package relies on DOMDocument, which can be finicky with malformed HTML. Always validate input:
      @$dom->loadHTML($html); // Suppress warnings for broken HTML
      
    • Use loadHTML() instead of load() for HTML strings to avoid strict XML parsing.
  2. Selector Limitations:

    • The package uses basic CSS selectors (not a full parser). Complex selectors like :nth-child may not work. Test thoroughly:
      // Works: remove all <p> tags
      $manipulator->removeElementsByTagName('p');
      
      // May fail: remove every other <tr>
      $manipulator->removeElementsBySelector('tr:nth-of-type(even)');
      
  3. Attribute Conflicts:

    • Setting attributes with setAttribute() will overwrite existing values. Use toggleAttribute() for conditional logic:
      $manipulator->toggleAttribute('input[type="checkbox"]', 'disabled', true);
      
  4. Memory Usage:

    • Large DOM trees (e.g., scraping entire pages) can bloat memory. Process in chunks or use DOMXPath for targeted queries.

Debugging

  • Inspect the DOM:
    echo $dom->saveHTML(); // Full output
    echo $dom->saveHTML($node); // Inspect a specific node
    
  • Enable Error Reporting:
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    $errors = libxml_get_errors();
    // Handle errors...
    

Extension Points

  1. Custom Selectors: Extend the package by adding selector logic (e.g., regex-based matching):

    $manipulator->customRemove(function ($node) {
        return preg_match('/unwanted-text/', $node->nodeValue);
    });
    
  2. Event Hooks: Intercept DOM manipulations by subclassing DomManipulations:

    class CustomDomManipulations extends DomManipulations {
        public function removeElementsByTagName($tagName) {
            // Pre-processing logic
            parent::removeElementsByTagName($tagName);
            // Post-processing logic
        }
    }
    
  3. Laravel Service Provider: Bind a configured instance:

    $this->app->singleton(DomManipulations::class, function ($app) {
        $dom = new \DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->substituteEntities = true;
        return new DomManipulations($dom);
    });
    

Performance Tips

  • Reuse DOMDocument: Avoid recreating the DOM for each manipulation:
    $dom = new \DOMDocument();
    $manipulator = new DomManipulations($dom);
    // Reuse $manipulator for multiple operations
    
  • Use XPath for Complex Queries: Combine with DOMXPath for better performance:
    $xpath = new \DOMXPath($dom);
    $nodes = $xpath->query('//div[contains(@class, "sidebar")]');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor