Weave 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

Dom Laravel Package

phpgt/dom

A modern DOM API for PHP built on the native DOMDocument, giving you browser-style, standardised object-oriented DOM manipulation server-side. Treat HTML files as templates and ready-process pages for browsers, webservers and CDNs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require phpgt/dom
    

    No additional configuration is required—just autoload via Composer.

  2. First Use Case: Parse and manipulate HTML/XML with a modern, chainable API:

    use Phpgt\Dom\Document;
    
    $html = '<div class="container"><h1>Hello</h1><p>World</p></div>';
    $dom = Document::loadHtml($html);
    
    // Query and modify
    $dom->query('h1')->setText('Updated Title');
    echo $dom->saveHtml();
    
  3. Key Entry Points:

    • Document::loadHtml() / Document::loadXml() – Parse strings or files.
    • $dom->query() – Select elements (CSS selectors or XPath).
    • $element->setAttribute() / $element->remove() – Modify structure/content.

Implementation Patterns

Common Workflows

  1. Scraping & Data Extraction:

    $dom = Document::loadHtml(file_get_contents('https://example.com'));
    $titles = $dom->query('article h2')->map(fn($el) => $el->textContent);
    
  2. Dynamic HTML Generation:

    $dom = new Document();
    $dom->appendChild($dom->createElement('div'))
        ->setAttribute('id', 'dynamic-content')
        ->appendChild($dom->createTextNode('Dynamic!'));
    
  3. Building Blocks with Document Fragments: Compose reusable chunks of markup, including empty ones, and append them in a single operation:

    $fragment = $dom->createDocumentFragment();
    // ...optionally populate: $fragment->appendXml('<li>Item</li>');
    
    // appendChild returns the fragment, so you can chain/work with it directly
    $returned = $dom->appendChild($fragment);
    
  4. Integration with Laravel:

    • Blade Templates: Use Document to pre-process HTML before rendering:
      $dom = Document::loadHtml(view('partials.header')->render());
      $dom->query('.logo')->setAttribute('src', asset('new-logo.png'));
      echo $dom->saveHtml();
      
    • Form Handling: Sanitize/modify user-submitted HTML:
      $cleaned = Document::loadHtml($request->input('html_content'))
          ->query('script')->remove()
          ->saveHtml();
      
  5. Testing:

    $this->assertEquals(
        '<div>Test</div>',
        Document::loadHtml('<div>Test</div>')->saveHtml()
    );
    

Performance Tips

  • Reuse Documents: Instantiate once and reuse for multiple operations.
  • Batch Queries: Chain queries to avoid repeated parsing:
    $dom->query('.item')->each(fn($el) => $el->setAttribute('data-id', $el->id));
    

Gotchas and Tips

Pitfalls

  1. XPath vs. CSS Selectors:

    • CSS selectors (e.g., query('div > p')) are faster but less powerful than XPath.
    • Use XPath for complex queries (e.g., query('//div[@class="nested"]//a')).
  2. Namespace Handling:

    • XML namespaces require explicit declaration:
      $dom = Document::loadXml('<svg xmlns="http://www.w3.org/2000/svg">...</svg>');
      $dom->registerNamespace('svg', 'http://www.w3.org/2000/svg');
      $dom->query('svg|circle')->remove();
      
  3. HTML5 Quirks:

    • Self-closing tags (e.g., <img />) may render differently in saveHtml(). Use:
      $dom->setFormatOutput(true); // Pretty-print with proper tag closing.
      
  4. Memory Usage:

    • Large documents (e.g., 10MB+) may cause high memory usage. Stream parsing with DOMDocument::loadHTMLFile() (native) as a fallback.

Debugging

  • Inspect Elements:
    $dom->query('body')->each(fn($el) => dump($el->outerHTML));
    
  • Validate XML:
    $dom->validate(); // Throws exception on malformed XML.
    

Extension Points

  1. Custom Elements: Extend Phpgt\Dom\Element for domain-specific methods:

    class ArticleElement extends Element {
        public function getTitle(): string {
            return $this->query('h1')->textContent;
        }
    }
    
  2. Event Listeners: Hook into DOM events (e.g., post-load) via traits or decorators.

  3. Integration with Guzzle: Combine with HTTP clients for headless scraping:

    $html = $client->request('GET', $url)->getBody();
    $dom = Document::loadHtml($html);
    

Configuration Quirks

  • Default Doctype: Document::loadHtml() auto-detects HTML5; force a doctype with:
    $dom = new Document();
    $dom->appendChild($dom->createProcessingInstruction('xml', 'version="1.0"'));
    

Version Notes

  • v4.2.2: appendChild() with an empty DocumentFragment now correctly returns the fragment instead of a falsy/inconsistent value. If you build fragments conditionally (populating them only when data exists), pin to ^4.2.2 and rely on the returned fragment for chaining. This is a drop-in patch—no API changes or deprecations—so existing upgrade paths are unaffected.
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.
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console