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 Html Parser Laravel Package

paquettg/php-html-parser

Fast, lightweight HTML parser for PHP that turns messy markup into a DOM-like tree. Crawl and scrape pages, query elements with CSS selectors, and extract text/attributes easily. Works with imperfect HTML and focuses on simple, fluent usage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require paquettg/php-html-parser
    

    No additional configuration is needed—just require the package in your project.

  2. First Use Case: Parsing HTML

    use PHPHtmlParser\Dom;
    
    $html = '<div class="example"><h1>Hello</h1><p>World</p></div>';
    $dom = new Dom();
    $dom->loadFromString($html);
    
    // Extract the h1 text
    echo $dom->find('h1', 0)->text; // Output: "Hello"
    
  3. Where to Look First

    • Class Documentation (if available).
    • Dom class methods: loadFromString(), loadFromFile(), find(), getAttribute(), setAttribute(), etc.
    • Selector syntax (similar to jQuery, e.g., 'div.example', 'h1 > p').

Implementation Patterns

Common Workflows

  1. Scraping Web Pages

    $dom = new Dom();
    $dom->loadFromUrl('https://example.com');
    
    // Extract all links
    $links = $dom->find('a');
    foreach ($links as $link) {
        echo $link->href . "\n";
    }
    
  2. Modifying HTML

    $dom = new Dom();
    $dom->loadFromString('<div id="old">Old Content</div>');
    
    // Update content and attributes
    $dom->find('div', 0)->setAttribute('id', 'new');
    $dom->find('div', 0)->text = 'New Content';
    
    echo $dom->saveHtml(); // Output: '<div id="new">New Content</div>'
    
  3. Dynamic Selectors with Data Attributes

    $dom->loadFromString('<div data-id="123">Item</div>');
    $item = $dom->find('[data-id="123"]', 0);
    echo $item->text; // Output: "Item"
    
  4. Iterating and Filtering Nodes

    $dom->loadFromString('<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>');
    $fruits = $dom->find('li');
    
    // Filter fruits starting with 'B'
    $bananas = array_filter($fruits, fn($node) => str_starts_with($node->text, 'B'));
    
  5. Handling Forms

    $dom->loadFromString('<form><input name="email" value="test@example.com"></form>');
    $email = $dom->find('input[name="email"]', 0)->getAttribute('value');
    

Integration Tips

  • Laravel Blade Integration: Use Str::of() with PHPHtmlParser for dynamic HTML manipulation in Blade templates.
    use Illuminate\Support\Str;
    use PHPHtmlParser\Dom;
    
    $html = '<div class="content">...</div>';
    $dom = new Dom();
    $dom->loadFromString($html);
    
    // Modify HTML in Blade
    echo Str::of($dom->saveHtml())->replace('content', 'updated-content');
    
  • Caching Parsed HTML: Cache parsed Dom objects for performance-critical scraping tasks.
    $cacheKey = 'parsed_html_' . md5($url);
    $dom = Cache::remember($cacheKey, now()->addHours(1), function() use ($url) {
        $dom = new Dom();
        $dom->loadFromUrl($url);
        return $dom;
    });
    

Gotchas and Tips

Pitfalls

  1. Selector Limitations

    • Unlike jQuery, some advanced CSS selectors (e.g., :nth-child(odd)) may not work as expected. Test selectors thoroughly.
    • Workaround: Use find() with loops and manual filtering if needed.
  2. Malformed HTML

    • The parser may behave unpredictably with broken HTML (e.g., unclosed tags). Use loadFromString() with Dom::PARSER_HTML flag for strict parsing:
      $dom->loadFromString($html, Dom::PARSER_HTML);
      
  3. Attribute Case Sensitivity

    • Attributes like class or for are case-insensitive in HTML but may behave differently in selectors. Stick to lowercase for consistency.
  4. Memory Usage

    • Parsing large HTML documents (e.g., entire web pages) can consume significant memory. Use loadFromUrl() with streaming or chunking for large files.
  5. XPath vs. Selectors

    • The package prioritizes selector-based queries. For complex traversals, consider combining with DOMXPath:
      $xpath = new DOMXPath($dom->getDOM());
      $nodes = $xpath->query('//div[@class="complex"]');
      

Debugging Tips

  • Inspect Nodes: Use saveHtml() to debug the current state of the DOM:
    echo $dom->saveHtml(); // Log or dump this for debugging
    
  • Selector Validation: Test selectors in browser DevTools first to ensure they match the expected structure.
  • Error Handling: Wrap parsing in try-catch blocks for network requests or file operations:
    try {
        $dom->loadFromUrl($url);
    } catch (\Exception $e) {
        Log::error("Failed to parse URL: {$url}", ['error' => $e->getMessage()]);
    }
    

Extension Points

  1. Custom Selector Logic Extend the parser by implementing your own selector logic using Dom::find() and array filtering:

    $customNodes = array_filter($dom->find('*'), function($node) {
        return str_contains($node->className, 'custom-class');
    });
    
  2. Event Listeners Hook into the parsing process by overriding the Dom class or using traits for pre/post-processing:

    class CustomDom extends Dom {
        public function loadFromString($string, $parser = null) {
            $this->preProcess($string);
            parent::loadFromString($string, $parser);
        }
    
        private function preProcess($html) {
            // Modify HTML before parsing (e.g., add missing tags)
        }
    }
    
  3. Integration with Laravel Events Dispatch events after parsing or modifying HTML:

    event(new HtmlParsed($dom, $url));
    
  4. Performance Optimization

    • For repeated parsing, reuse Dom instances instead of recreating them.
    • Use loadFromFile() for static HTML files to avoid re-downloading content.
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