### Quick Start: Load HTML and Find Elements with DiDOM Source: https://github.com/imangazaliev/didom/blob/master/README.md A basic example demonstrating how to load an HTML document from a URL and find all elements with the class 'post' using DiDOM. It then iterates through the found elements and prints their text content. ```php use DiDom\Document; $document = new Document('http://www.news.com/', true); $posts = $document->find('.post'); foreach($posts as $post) { echo $post->text(), "\n"; } ``` -------------------------------- ### Install DiDOM using Composer Source: https://github.com/imangazaliev/didom/blob/master/README.md This snippet shows the Composer command to install the DiDOM library. Composer is a dependency manager for PHP, and this command will add DiDOM to your project's dependencies. ```bash composer require imangazaliev/didom ``` -------------------------------- ### CSS Class and Style Attribute Management - PHP Source: https://context7.com/imangazaliev/didom/llms.txt Provides examples for manipulating CSS classes and inline styles on HTML elements using DiDom. This includes adding, removing, checking for, and retrieving CSS classes, as well as setting, getting, removing, and retrieving inline style properties. ```php 'container active']); // Get class attribute manager $classes = $div->classes(); // Add class $classes->add('featured'); $classes->add(['highlighted', 'premium']); // Remove class $classes->remove('active'); // Check if has class if ($classes->contains('container')) { echo "Has container class"; } // Get all classes $allClasses = $classes->getAll(); // ['container', 'featured', 'highlighted', 'premium'] // Get style attribute manager $style = $div->style(); // Set style property $style->set('color', 'red'); $style->set('font-size', '14px'); $style->setMultiple(['margin' => '10px', 'padding' => '5px']); // Get style property $color = $style->get('color'); // 'red' // Remove style property $style->remove('color'); // Get all styles $allStyles = $style->getAll(); // ['font-size' => '14px', 'margin' => '10px', ...] ``` -------------------------------- ### Load HTML/XML Content using Separate Methods in DiDOM Source: https://github.com/imangazaliev/didom/blob/master/README.md Shows alternative methods for loading HTML or XML content into a DiDOM Document. It demonstrates `loadHtml`, `loadHtmlFile`, `loadXml`, and `loadXmlFile`, including examples of passing libxml options for advanced parsing control. ```php $document = new Document(); $document->loadHtml($html); $document->loadHtmlFile('page.html'); $document->loadHtmlFile('http://www.example.com/'); // With options $document->loadHtml($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $document->loadHtmlFile($url, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $document->loadXml($xml, LIBXML_PARSEHUGE); $document->loadXmlFile($url, LIBXML_PARSEHUGE); ``` -------------------------------- ### Navigate DOM Nodes: Parent, Child, Sibling - PHP Source: https://context7.com/imangazaliev/didom/llms.txt Demonstrates how to navigate through parent, child, and sibling nodes in a DiDom document. It includes examples for getting parent elements, ancestors, children by index or position, and siblings. This functionality is crucial for traversing and selecting related elements within the DOM tree. ```php
'; $document = new Document($html); // Get parent element $activeLink = $document->first('.active a'); $parentLi = $activeLink->parent(); $parentUl = $parentLi->parent(); // Get closest ancestor matching selector $nav = $activeLink->closest('nav'); $activeItem = $activeLink->closest('li.active'); // Get children $menu = $document->first('ul.menu'); $children = $menu->children(); // All child nodes $firstChild = $menu->firstChild(); $lastChild = $menu->lastChild(); $secondChild = $menu->child(1); // Get child by index // Check if has children if ($menu->hasChildren()) { echo "Menu has items"; } // Get siblings $activeLi = $document->first('li.active'); $prevSibling = $activeLi->previousSibling(); $nextSibling = $activeLi->nextSibling(); // Get all siblings $prevSiblings = $activeLi->previousSiblings(); $nextSiblings = $activeLi->nextSiblings(); // Get siblings with selector $prevLinks = $activeLi->previousSibling('li', 'DOMElement'); $nextLinks = $activeLi->nextSibling('li', 'DOMElement'); // Search within element context $menuItems = $menu->find('li'); $firstLink = $menu->first('a'); // Search in document (affects original document) $title = $document->first('nav')->firstInDocument('a'); $title->remove(); // This removes from the original document ``` -------------------------------- ### Working with Element Attributes in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Demonstrates methods for creating, updating, getting, checking existence, and removing attributes from DOM elements. Supports both direct method calls and magic methods for attribute manipulation. ```php $element->setAttribute('name', 'username'); ``` ```php $element->attr('name', 'username'); ``` ```php $element->name = 'username'; ``` ```php $username = $element->getAttribute('value'); ``` ```php $username = $element->attr('value'); ``` ```php $username = $element->name; ``` ```php if ($element->hasAttribute('name')) { // code } ``` ```php if (isset($element->name)) { // code } ``` ```php $element->removeAttribute('name'); ``` ```php unset($element->name); ``` -------------------------------- ### Convert CSS to XPath and Manage Cache in PHP Source: https://context7.com/imangazaliev/didom/llms.txt Provides examples of converting CSS selectors into XPath expressions using the DiDom library. It covers basic conversion, compilation with explicit types, and extracting segments of a CSS selector for manual XPath construction. It also demonstrates how to manage the internal cache for compiled queries. ```php p.intro'); echo $xpath; // "//div[contains(concat(' ', normalize-space(@class), ' '), ' container ')]/p[...]/text()" // Compile with explicit type $xpath = Query::compile('//div[@class="container"]', Query::TYPE_XPATH); echo $xpath; // Returns as-is for XPath // CSS to XPath conversion $xpath = Query::cssToXpath('a[href^=https]'); echo $xpath; // Get selector segments $segments = Query::getSegments('div#main.container.active[data-value="test"]'); /* Returns: [ 'selector' => 'div#main.container.active[data-value="test"]', 'tag' => 'div', 'id' => 'main', 'classes' => ['container', 'active'], 'attributes' => ['data-value' => 'test'] ] */ // Build XPath from segments $xpath = Query::buildXpath($segments); // Manage query cache $compiled = Query::getCompiled(); Query::setCompiled(['div.test' => '//div[@class="test"]']); ?> ``` -------------------------------- ### Getting Formatted HTML Output Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the HTML content of a document, with options for formatting. To format the HTML of a specific element, it must first be converted into a document using `toDocument()`. ```php $posts = $document->find('.post'); echo $posts[0]->html(); $html = (string) $posts[0]; $html = $document->format()->html(); $html = $element->toDocument()->format()->html(); ``` -------------------------------- ### PHP DiDom: Element Creation and Modification Source: https://context7.com/imangazaliev/didom/llms.txt Provides examples of programmatically creating new HTML/XML elements and modifying the DOM structure using DiDom. It covers creating elements from tags, selectors, text nodes, comments, CDATA sections, appending, prepending, inserting before/after, and inserting siblings. ```php createElement('div', 'Content', ['class' => 'container', 'id' => 'main']); // Create element by selector $button = $document->createElementBySelector('button.btn.btn-primary#submit', 'Submit'); // Creates: // Create text node $textNode = $document->createTextNode('Plain text content'); // Create comment $comment = $document->createComment('This is a comment'); // Create CDATA section $cdata = $document->createCdataSection(''); // Static element creation $span = Element::create('span', 'Text', ['class' => 'highlight']); $link = Element::createBySelector('a.external[target=_blank]', 'External Link'); // Append child to document $document->appendChild($div); // Append multiple children $list = new Element('ul'); $item1 = new Element('li', 'Item 1'); $item2 = new Element('li', 'Item 2'); $list->appendChild([$item1, $item2]); // Prepend child (add at beginning) $firstItem = new Element('li', 'First Item'); $list->prependChild($firstItem); // Insert before/after $newItem = new Element('li', 'New Item'); $list->insertBefore($newItem, $item2); $list->insertAfter($newItem, $item1); // Insert sibling $header = new Element('h1', 'Header'); $div->insertSiblingBefore($header); $footer = new Element('footer', 'Footer'); $div->insertSiblingAfter($footer); ?> ``` -------------------------------- ### Getting XML Output Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the XML representation of a document or a specific element using the `xml()` method. This method is useful for serializing the DOM structure into an XML string. ```php echo $document->xml(); echo $document->first('book')->xml(); ``` -------------------------------- ### Getting Text Content Source: https://github.com/imangazaliev/didom/blob/master/README.md Extracts the plain text content from an element using the `text()` method. This method recursively gets all the text from the element and its children, stripping out any HTML tags. ```php $posts = $document->find('.post'); echo $posts[0]->text(); ``` -------------------------------- ### Get Owner Document in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the owner document of a given DOM element. This is useful for checking if two elements belong to the same document. Requires a parsed Document object and a found element. ```php $document = new Document($html); $element = $document->find('input[name=email]')[0]; $document2 = $element->ownerDocument(); // bool(true) var_dump($document->is($document2)); ``` -------------------------------- ### Complete Web Scraping Workflow in PHP with DiDom Source: https://context7.com/imangazaliev/didom/llms.txt This PHP script demonstrates a full web scraping process using the DiDom library. It loads a webpage, finds multiple article elements, and extracts various pieces of information such as title, URL, excerpt, author, date, tags, and featured status. It also counts comments and then iterates through the collected data to display it. Dependencies include the DiDom library installed via Composer. ```php find('article.post'); foreach ($articleElements as $article) { // Extract title $titleElement = $article->first('h2.title'); $title = $titleElement ? $titleElement->text() : 'No title'; // Extract link $link = $article->first('a.read-more'); $url = $link ? $link->getAttribute('href') : ''; // Extract excerpt $excerpt = $article->first('.excerpt'); $excerptText = $excerpt ? trim($excerpt->text()) : ''; // Extract metadata $author = $article->first('.author'); $date = $article->first('.date'); // Extract all tags $tags = []; $tagElements = $article->find('.tags a'); foreach ($tagElements as $tag) { $tags[] = $tag->text(); } // Check if featured $isFeatured = $article->matches('.featured'); // Count comments $commentCount = $article->count('.comment'); $articles[] = [ 'title' => $title, 'url' => $url, 'excerpt' => $excerptText, 'author' => $author ? $author->text() : 'Unknown', 'date' => $date ? $date->getAttribute('datetime') : '', 'tags' => $tags, 'featured' => $isFeatured, 'comments' => $commentCount ]; } // Process results foreach ($articles as $article) { echo "Title: {$article['title']}\n"; echo "URL: {$article['url']}\n"; echo "Tags: " . implode(', ', $article['tags']) . "\n"; echo "Comments: {$article['comments']}\n"; echo str_repeat('-', 50) . "\n"; } ``` -------------------------------- ### Getting Inner HTML of an Element Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the inner HTML content of an element using the `innerHtml()` method. If you need to get the inner HTML of a document, convert it to an element first using `toElement()`. ```php $innerHtml = $element->innerHtml(); $innerHtml = $document->toElement()->innerHtml(); ``` -------------------------------- ### Getting Element Tag Name Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the tag name of an element using the `tagName()` method. This method returns the HTML tag name of the element as a string. ```php $element->tagName(); ``` -------------------------------- ### Document Output and Formatting: HTML/XML Export - PHP Source: https://context7.com/imangazaliev/didom/llms.txt Details how to export DiDom documents and elements as HTML or XML strings. Covers getting the full HTML/XML output, formatted output with indentation, and extracting HTML content from specific elements (outer and inner HTML). ```phpContent