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

Dom Laravel Package

phpgt/dom

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. 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();
      
  4. 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"'));
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle