### 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). ```php Page

Content

'; $document->loadHtml($html); // Get HTML output $output = $document->html(); echo $output; // Get formatted HTML (with indentation) $formatted = $document->format()->html(); echo $formatted; // Format element output $element = $document->first('div'); $elementHtml = $element->toDocument()->format()->html(); // Get XML output $document->loadXml('Value'); $xml = $document->xml(); // Get XML with options $xml = $document->xml(LIBXML_NOEMPTYTAG); // Convert to string (uses appropriate format) $output = (string) $document; // Get element HTML $div = $document->first('div'); $divHtml = $div->html(); // Outer HTML $divInner = $div->innerHtml(); // Inner HTML only $divOuter = $div->outerHtml(); // Explicit outer HTML // Get text content $text = $document->text(); // All text without tags $divText = $div->text(); ``` -------------------------------- ### Get Parent Element in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the parent element of a given DOM element. This is useful for navigating up the DOM tree. It requires a parsed Document object and a found element. ```php $document = new Document($html); $input = $document->find('input[name=email]')[0]; var_dump($input->parent()); ``` -------------------------------- ### Get Sibling Elements in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves the previous and next sibling elements of a given DOM element. This helps in navigating adjacent elements in the DOM tree. It requires a parsed Document object and a found element. ```php $document = new Document($html); $item = $document->find('ul.menu > li')[1]; var_dump($item->previousSibling()); var_dump($item->nextSibling()); ``` -------------------------------- ### Get Child Elements in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Retrieves child elements, including text and comment nodes, of a given DOM element. Supports accessing children by index, first/last child, and retrieving all children. Requires a parsed Document object and a target element. ```php $html = '
FooBar
'; $document = new Document($html); $div = $document->first('div'); // element node (DOMElement) // string(3) "Bar" var_dump($div->child(1)->text()); // text node (DOMText) // string(3) "Foo" var_dump($div->firstChild()->text()); // comment node (DOMComment) // string(3) "Baz" var_dump($div->lastChild()->text()); // array(3) { ... } var_dump($div->children()); ``` -------------------------------- ### PHP DiDom: Element Attribute Manipulation Source: https://context7.com/imangazaliev/didom/llms.txt Explains how to manage element attributes using DiDom. This includes setting, getting, checking for existence, removing attributes, and utilizing magic methods for attribute access. It covers both direct method calls and shorthand attribute access. ```php 'email', 'type' => 'email', 'required' => 'required']; $input = new Element('input', null, $attributes); // Set attribute $input->setAttribute('placeholder', 'Enter your email'); $input->attr('class', 'form-control'); // Alternative method // Get attribute $name = $input->getAttribute('name'); // "email" $type = $input->attr('type'); // "email" $default = $input->getAttribute('value', 'default@example.com'); // Returns default if not exists // Check if attribute exists if ($input->hasAttribute('required')) { echo "This field is required"; } // Get all attributes $allAttrs = $input->attributes(); // ['name' => 'email', 'type' => 'email', 'required' => 'required', ...] // Get specific attributes $selectedAttrs = $input->attributes(['name', 'type']); // ['name' => 'email', 'type' => 'email'] // Remove attribute $input->removeAttribute('required'); // Remove all attributes except specified $input->removeAllAttributes(['name', 'type']); // Magic methods for attributes $input->id = 'email-input'; // Set using __set $id = $input->id; // Get using __get if (isset($input->id)) { // Check using __isset unset($input->id); // Remove using __unset } ?> ``` -------------------------------- ### Create DiDOM Document from String, File, or URL Source: https://github.com/imangazaliev/didom/blob/master/README.md Illustrates various ways to create a new DiDOM Document object. It covers initializing with an HTML string, loading from a local file, and fetching content from a URL. The constructor signature and parameter explanations are provided. ```php // From HTML string $document = new Document($html); // From file path $document = new Document('page.html', true); // From URL $document = new Document('http://www.example.com/', true); ``` -------------------------------- ### Creating a New Element Instance Source: https://github.com/imangazaliev/didom/blob/master/README.md Demonstrates creating a new `Element` instance in PHP. The constructor accepts the tag name, an optional value, and an optional array of attributes. It can also be initialized from a `DOMElement` object. ```php use DiDom\Element; $element = new Element('span', 'Hello'); // Outputs "Hello" echo $element->html(); $attributes = ['name' => 'description', 'placeholder' => 'Enter description of item']; $element = new Element('textarea', 'Text', $attributes); use DOMElement; $domElement = new DOMElement('span', 'Hello'); $element = new Element($domElement); ``` -------------------------------- ### PHP Test Script for HTML Parser Benchmarking Source: https://github.com/imangazaliev/didom/wiki/Comparison-with-other-parsers-(1.0) This PHP script serves as the core testing utility. It loads an HTML file, measures the time and memory usage for a 'parsing code' section (to be filled in by specific parser implementations), and appends the results to 'time.txt' and 'memory.txt'. It requires the Composer autoloader and takes the filename as a command-line argument. ```php require 'vendor/autoload.php'; $filepath = __DIR__.'/../files/'.$argv[1].'.html'; $html = file_get_contents($filepath); $startMemory = memory_get_usage(); $startTime = microtime(true); // parsing code $time = microtime(true) - $startTime; $memory = memory_get_usage() - $startMemory; file_put_contents(__DIR__.'/time.txt', $time . PHP_EOL, FILE_APPEND); file_put_contents(__DIR__.'/memory.txt', $memory . PHP_EOL, FILE_APPEND); ``` -------------------------------- ### Load HTML/XML Documents in PHP with DiDOM Source: https://context7.com/imangazaliev/didom/llms.txt Demonstrates loading HTML or XML documents from strings, files, or URLs using the DiDOM library. It covers various loading methods, encoding specifications, and libxml options for advanced control. ```php

Hello World

'; $document = new Document($html); // Load HTML from file $document = new Document('page.html', true); // Load HTML from URL $document = new Document('https://example.com/', true); // Load with custom encoding $document = new Document($html, false, 'UTF-8', Document::TYPE_HTML); // Alternative: Load using methods $document = new Document(); $document->loadHtml($html); $document->loadHtmlFile('page.html'); $document->loadHtmlFile('https://example.com/'); // Load XML $xml = 'Value'; $document->loadXml($xml); $document->loadXmlFile('data.xml'); // Load with libxml options $document->loadHtml($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); ?> ``` -------------------------------- ### Find Elements Using CSS Selectors in PHP with DiDOM Source: https://context7.com/imangazaliev/didom/llms.txt Illustrates how to find HTML elements using CSS selectors with the DiDOM library. It covers finding multiple elements, single elements by ID, filtering by attributes, complex selectors, and checking element existence. ```php

First Post

This is the first post.

Read more

Second Post

This is the second post.

'; $document = new Document($html); // Find all elements with class "post" $posts = $document->find('.post'); foreach ($posts as $post) { echo $post->text() . "\n"; } // Find element by ID $firstPost = $document->find('#post-1')[0]; // Find by attribute $links = $document->find('a[href^=https]'); // Complex selectors $featuredPosts = $document->find('article.post.featured'); $paragraphs = $document->find('.post > .content'); // Find with attribute contains $externalLinks = $document->find('a[href*=example.com]'); // Get first matching element $firstArticle = $document->first('article.post'); echo $firstArticle->text(); // Check if element exists if ($document->has('.post')) { echo "Posts found!"; } // Count elements $postCount = $document->count('.post'); echo "Total posts: " . $postCount; ?> ``` -------------------------------- ### Working with Cache in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Manages the cache for XPath expressions generated from CSS selectors. Allows retrieving the compiled cache and setting custom cache entries. Requires the `DiDom\Query` class. ```php use DiDom\Query; ... $xpath = Query::compile('h2'); $compiled = Query::getCompiled(); // array('h2' => '//h2') var_dump($compiled); ``` ```php Query::setCompiled(['h2' => '//h2']); ``` -------------------------------- ### Search Elements in DiDOM using CSS Selectors and XPath Source: https://github.com/imangazaliev/didom/blob/master/README.md Demonstrates how to find elements within a DiDOM Document using both CSS selectors and XPath expressions. It shows the usage of the `find()` method with explicit type specification and the shorthand `xpath()` method. The ability to search within a specific element is also illustrated. ```php use DiDom\Document; use DiDom\Query; // CSS selector $posts = $document->find('.post'); // XPath $posts = $document->find("//div[contains(@class, 'post')]", Query::TYPE_XPATH); // Using xpath() method $posts = $document->xpath("//*[contains(concat(' ', normalize-space(@class), ' '), ' post ')]"); // Search within an element echo $document->find('nav')[0]->first('ul.menu')->xpath('//li')[0]->text(); ``` -------------------------------- ### Supported Selectors in DiDom Source: https://github.com/imangazaliev/didom/blob/master/README.md Illustrates the diverse range of CSS selectors supported by DiDom, including tags, classes, IDs, attributes, pseudo-classes like `:first-`, `:last-`, `:nth-child()`, `:contains()`, `:has()`, and attribute selectors for matching specific values or patterns. ```php // all links $document->find('a'); // any element with id = "foo" and "bar" class $document->find('#foo.bar'); // any element with attribute "name" $document->find('[name]'); // the same as $document->find('*[name]'); // input field with the name "foo" $document->find('input[name=foo]'); $document->find('input[name='bar']'); $document->find('input[name="baz"]'); // any element that has an attribute starting with "data-" and the value "foo" $document->find('*[^data-=foo]'); // all links starting with https $document->find('a[href^=https]'); // all images with the extension png $document->find('img[src$=png]'); // all links containing the string "example.com" $document->find('a[href*=example.com]'); // text of the links with "foo" class $document->find('a.foo::text'); // address and title of all the fields with "bar" class $document->find('a.bar::attr(href|title)'); ``` -------------------------------- ### Configure DiDom Document Parsing in PHP Source: https://context7.com/imangazaliev/didom/llms.txt Shows advanced configuration options for the DiDom Document class, including preserving whitespace during parsing, specifying character encoding, registering XML namespaces, and accessing underlying DOMDocument properties. It also covers methods for converting between Document and Element objects and cloning nodes. ```php

Content

'; // Preserve whitespace $document = new Document(); $document->preserveWhiteSpace(true); // Default is false $document->loadHtml($html); // Load with encoding $document = new Document($html, false, 'UTF-8'); // Register XML namespace $document->registerNamespace('custom', 'http://example.com/schema'); // Get document properties $type = $document->getType(); // 'html' or 'xml' $encoding = $document->getEncoding(); // 'UTF-8' // Get underlying DOMDocument $domDocument = $document->getDocument(); // Get document element $rootElement = $document->getElement(); // Convert document to element $element = $document->toElement(); // Get owner document from element $element = $document->first('div'); $ownerDoc = $element->ownerDocument(); // Clone node $cloned = $element->cloneNode(true); // Deep clone with children $shallow = $element->cloneNode(false); // Shallow clone without children ?> ``` -------------------------------- ### Creating a New Element using createElement() Source: https://github.com/imangazaliev/didom/blob/master/README.md Creates a new element within a `Document` object using the `createElement()` method. This method is convenient for adding new nodes to an existing DOM structure. ```php $document = new Document($html); $element = $document->createElement('span', 'Hello'); ``` -------------------------------- ### Chained Element Searching Source: https://github.com/imangazaliev/didom/blob/master/README.md Demonstrates how to chain multiple find operations to navigate and extract specific text content from nested elements within a document. This method can involve multiple queries. ```php echo $document->find('nav')[0]->first('ul.menu')->xpath('//li')[0]->text(); ``` -------------------------------- ### Check Element Match and Compare Nodes in PHP Source: https://context7.com/imangazaliev/didom/llms.txt Demonstrates how to check if an element matches a given CSS selector, perform strict matching, and compare if two variables refer to the same DOM node or document instance using the DiDom library. This is useful for verifying element properties and relationships within the DOM structure. ```php

Content

'; $document = new Document($html); $div = $document->first('div'); // Check if element matches selector if ($div->matches('div.container')) { echo "Matches!"; } // Strict matching (exact match, no additional attributes) if ($div->matches('div#main.container.active', true)) { echo "Exact match!"; } // Match any element if ($div->matches('*')) { echo "Always true"; } // Compare elements (check if same node) $div1 = $document->first('div'); $div2 = $document->first('div'); $div3 = $document->first('p'); if ($div1->is($div1)) { echo "Same element"; // true } if ($div1->is($div2)) { echo "Same element"; // true (points to same node) } if ($div1->is($div3)) { echo "Same element"; // false (different nodes) } // Compare documents $doc1 = new Document($html); $doc2 = new Document($html); $doc3 = $doc1; if ($doc1->is($doc3)) { echo "Same document"; // true } if ($doc1->is($doc2)) { echo "Same document"; // false (different instances) } ?> ``` -------------------------------- ### Search within Source Document with findInDocument() Source: https://github.com/imangazaliev/didom/blob/master/README.md Uses `findInDocument()` and `firstInDocument()` to search for elements directly within the source document, ensuring that subsequent modifications affect the original document. These methods are essential for modifying elements in place. ```php // nothing will happen $document->first('head')->first('title')->remove(); // but this will do $document->first('head')->firstInDocument('title')->remove(); ``` -------------------------------- ### Find Elements Using XPath in PHP with DiDOM Source: https://context7.com/imangazaliev/didom/llms.txt Shows how to locate HTML elements using XPath expressions with the DiDOM library. This includes finding elements by attributes, using conditions, and specifying element positions within the DOM tree. ```php
  • Home
  • About
  • Contact
  • '; $document = new Document($html); // Find using XPath $menuItems = $document->find('//ul[@class="menu"]/li', Query::TYPE_XPATH); foreach ($menuItems as $item) { echo $item->text() . "\n"; } // Alternative: Use xpath() method $links = $document->xpath('//a[@href]'); foreach ($links as $link) { echo $link->getAttribute('href') . "\n"; } // Complex XPath with conditions $aboutLink = $document->xpath('//a[contains(@href, "about")]'); // XPath with position $firstMenuItem = $document->xpath('(//ul[@class="menu"]/li)[1]'); ?> ``` -------------------------------- ### PHP DiDom: Advanced Filtering with Pseudo-classes Source: https://context7.com/imangazaliev/didom/llms.txt Demonstrates advanced filtering techniques in DiDom using CSS pseudo-classes like :first-child, :last-child, :nth-child, :contains, :empty, :not-empty, and :has. These selectors allow for precise targeting of elements based on their position, content, or children. ```php
  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Text with keyword inside

    Another paragraph

    '; $document = new Document($html); // First child $firstItem = $document->find('li:first-child')[0]; echo $firstItem->text(); // "Item 1" // Last child $lastItem = $document->find('li:last-child')[0]; echo $lastItem->text(); // "Item 4" // Nth child $secondItem = $document->find('li:nth-child(2)')[0]; echo $secondItem->text(); // "Item 2" // Odd/even children $oddItems = $document->find('li:nth-child(odd)'); $evenItems = $document->find('li:nth-child(even)'); // Contains text $matching = $document->find('p:contains("keyword")'); // Empty elements $emptyParagraphs = $document->find('p:empty'); // Not empty $nonEmptyParagraphs = $document->find('p:not-empty'); // Has selector (contains child elements) $divsWithSpan = $document->find('div:has(span)'); ?> ``` -------------------------------- ### Verify Element Existence with has() Source: https://github.com/imangazaliev/didom/blob/master/README.md Checks if an element matching the given selector exists in the document. It's more efficient to combine finding and checking for existence in a single operation if the element is needed afterwards. ```php if ($document->has('.post')) { // code } ``` ```php if (count($elements = $document->find('.post')) > 0) { // code } ``` -------------------------------- ### Check Node Types in DOM in PHP Source: https://context7.com/imangazaliev/didom/llms.txt Illustrates how to determine the type of each node within the DOM, such as element nodes, text nodes, comment nodes, and CDATA sections. It also shows how to retrieve the tag name of element nodes and the line number where a node was found, which is beneficial for debugging and detailed DOM analysis. ```php Text contentSpan content
    CDATA content
    '; $document = new Document($html); $div = $document->first('div'); // Get all children (including text nodes, comments, etc.) $children = $div->children(); foreach ($children as $child) { if ($child->isElementNode()) { echo "Element: " . $child->tagName() . "\n"; } if ($child->isTextNode()) { echo "Text: " . $child->text() . "\n"; } if ($child->isCommentNode()) { echo "Comment: " . $child->text() . "\n"; } if ($child->isCdataSectionNode()) { echo "CDATA: " . $child->text() . "\n"; } } // Get specific node types when traversing $span = $div->child(1); if ($span->isElementNode()) { echo "Tag name: " . $span->tagName(); } // Get line number (useful for debugging) $lineNo = $span->getLineNo(); echo "Element found at line: " . $lineNo; ?> ``` -------------------------------- ### DOM Element Removal and Replacement - PHP Source: https://context7.com/imangazaliev/didom/llms.txt Illustrates how to remove and replace elements within a DiDom document. This includes methods for removing individual elements, specific child elements, all child elements, and replacing existing elements with new ones or by moving existing elements. ```php

    Old Title

    Introduction

    Body content

    '; $document = new Document($html); // Remove element $oldTitle = $document->first('h1'); $oldTitle->remove(); // Remove using findInDocument (affects original document) $document->first('#content')->firstInDocument('.footer')->remove(); // Remove child $content = $document->first('#content'); $intro = $content->first('.intro'); $content->removeChild($intro); // Remove all children $content->removeChildren(); // Replace element $newTitle = new Element('h2', 'New Title'); $document->first('h1')->replace($newTitle); // Replace without cloning (move the element) $existingElement = $document->first('.body'); $document->first('.intro')->replace($existingElement, false); ``` -------------------------------- ### Count Children Matching Selector in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Counts the number of direct children of an element that match a given CSS selector. Can be called on the document itself or a specific element. Requires a Document or Element object and a CSS selector. ```php // prints the number of links in the document echo $document->count('a'); ``` ```php // prints the number of items in the list echo $document->first('ul')->count('li'); ``` -------------------------------- ### Comparing Elements in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Compares two DOM elements for identity. The `is()` method returns true if both elements refer to the exact same node in the DOM tree. Requires Element objects. ```php $element = new Element('span', 'hello'); $element2 = new Element('span', 'hello'); // bool(true) var_dump($element->is($element)); // bool(false) var_dump($element->is($element2)); ``` -------------------------------- ### Replacing Element in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Replaces an existing DOM element with a new one. This operation can only be performed on elements found directly within the document. Requires the element to be replaced and the new element. ```php $element = new Element('span', 'hello'); $document->find('.post')[0]->replace($element); ``` ```php // but this will do $document->first('head title')->replace($title); ``` -------------------------------- ### Check if Element Matches Selector in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Determines if a DOM element matches a given CSS selector. An optional second argument enables strict matching, requiring the element to match the selector exactly without other attributes. Requires an Element object and a CSS selector. ```php $element->matches('div#content'); // strict match // returns true if the element is a div with id equals content and nothing else // if the element has any other attributes the method returns false $element->matches('div#content', true); ``` -------------------------------- ### Appending Child Elements in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Appends one or more child elements to a parent element. Can append single elements or an array of elements. Requires an existing Element object to append to and the child Element(s) to append. ```php $list = new Element('ul'); $item = new Element('li', 'Item 1'); $list->appendChild($item); $items = [ new Element('li', 'Item 2'), new Element('li', 'Item 3'), ]; $list->appendChild($items); ``` -------------------------------- ### Adding Child Element in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Adds a child element to a parent element. Similar to `appendChild`, this method can add single or multiple child elements. Requires an existing Element object and the child Element(s). ```php $list = new Element('ul'); $item = new Element('li', 'Item 1'); $items = [ new Element('li', 'Item 2'), new Element('li', 'Item 3'), ]; $list->appendChild($item); $list->appendChild($items); ``` -------------------------------- ### Changing Element Value as Plain Text Source: https://github.com/imangazaliev/didom/blob/master/README.md Updates the text content of an element using the `setValue()` method. If the provided value contains HTML characters, they will be automatically encoded using `htmlentities()` to ensure it's treated as plain text. ```php $element->setValue('Foo'); // will be encoded like using htmlentities() $element->setValue('Foo'); ``` -------------------------------- ### Preserve Whitespace Option in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Enables or disables whitespace preservation when loading XML documents. By default, whitespace is not preserved. Call `preserveWhiteSpace()` on a Document instance before loading. ```php $document = new Document(); $document->preserveWhiteSpace(); $document->loadXml($xml); ``` -------------------------------- ### Removing Element in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Removes a DOM element from the document. Similar to replacing, removal is restricted to elements found directly within the document. Requires the element to be removed. ```php $document->find('.post')[0]->remove(); ``` ```php // but this will do $document->first('head title')->remove(); ``` -------------------------------- ### Check if Node is Element Node in PHP Source: https://github.com/imangazaliev/didom/blob/master/README.md Verifies if a given DOM node is specifically an element node (DOMElement). Returns a boolean. Requires a DOM node object. ```php $element->isElementNode(); ``` -------------------------------- ### Changing Inner XML Content Source: https://github.com/imangazaliev/didom/blob/master/README.md Replaces the inner XML content of an element with new XML markup using the `setInnerXml()` method. This is useful for updating or inserting XML fragments within an existing element. ```php $element->setInnerXml(' Foo BarHello world! ]]>'); ``` -------------------------------- ### PHP DiDom: Content Manipulation Source: https://context7.com/imangazaliev/didom/llms.txt Details methods for modifying the content of HTML/XML elements within DiDom. This includes setting inner HTML and XML, setting text values (with automatic HTML escaping), and retrieving different forms of content (text, inner HTML, outer HTML). ```php

    Old content

    '); // Set inner HTML $container = $document->first('#container'); $container->setInnerHtml('

    New Title

    New paragraph

    '); // Set inner XML (preserves XML entities and CDATA) $container->setInnerXml(''); // Set text value (automatically escapes HTML) $paragraph = new Element('p'); $paragraph->setValue('This will be escaped'); echo $paragraph->html(); //

    This <b>will be escaped</b>

    // Get text content $text = $container->text(); // Gets all text without HTML tags // Get inner HTML $innerHTML = $container->innerHtml(); // Get outer HTML $outerHtml = $container->html(); echo $outerHtml; // Includes the container element itself ?> ``` -------------------------------- ### Check if Element is a Text Node (PHP) Source: https://github.com/imangazaliev/didom/blob/master/README.md The `isTextNode` method checks if a given DOM element is a text node. It returns `true` if the element is a DOMText instance, and `false` otherwise. This is useful for differentiating text content from other element types. ```php $element->isTextNode(); ``` -------------------------------- ### Changing Inner HTML Content Source: https://github.com/imangazaliev/didom/blob/master/README.md Modifies the inner HTML content of an element using the `setInnerHtml()` method. This allows for replacing the existing HTML structure within an element with new HTML markup. ```php $element->setInnerHtml('Foo'); ``` -------------------------------- ### Check if Element is a Comment Node (PHP) Source: https://github.com/imangazaliev/didom/blob/master/README.md The `isCommentNode` method determines if a DOM element is a comment node. It returns `true` if the element is a DOMComment instance, and `false` otherwise. This method helps in identifying and processing comments within the DOM structure. ```php $element->isCommentNode(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.