DiDOM Documentation

repository·master·Indexed 24 days ago

https://github.com/imangazaliev/didom

A simple and fast HTML and XML parser for PHP. DiDOM provides a user-friendly API for traversing, searching, and manipulating DOM trees using CSS selectors and XPath. It includes features for web scraping, element modification, DOM tree navigation, and attribute management.

Tokens
8.3K
Snippets
19
Records
56
Agent score
68%

What's inside DiDOM

  1. How searching in elements works

    master

    Methods like find(), first(), xpath(), has(), and count() are available on both Document and Element instances, allowing for scoped searches.

    When you call find() on an Element, DiDOM creates a new document context for that search. This means if you attempt to modify or remove an element found via a scoped search, the changes might not reflect in the original document.

    To ensure modifications (like remove()) affect the original document, use the InDocument variants:

    • findInDocument()
    • firstInDocument()

    Warning: These methods only work for elements that belong to a document or were created via new Element(...). Otherwise, a LogicException is thrown.

  2. Search in the source document from an element

    master

    By default, calling find(), first(), or xpath() on an Element creates a new document context scoped to that element. If you need to perform a search that targets the original source document while starting from an element, use findInDocument() or firstInDocument().

    Warning: These methods only work for elements belonging to a document or elements created via new Element(...). Using them on detached elements throws a LogicException.

  3. Configure whitespace preservation

    master

    By default, whitespace between tags is not preserved. To enable whitespace preservation, you must call preserveWhiteSpace() on the Document instance before loading the XML/HTML content.

    $document = new Document();
    $document->preserveWhiteSpace();
    $document->loadXml($xml);
  4. Quick start with DiDOM

    master

    To perform basic web scraping, instantiate a DiDom\Document with a URL, use find() with a CSS selector to retrieve elements, and iterate through them to extract text.

    use DiDom\Document;
    
    $document = new Document('http://www.news.com/', true);
    
    $posts = $document->find('.post');
    
    foreach($posts as $post) {
        echo $post->text(), "\n";
    }
  5. How the Document class works

    master

    The Document class acts as the primary entry point and manager for a DOM tree in DiDOM. It wraps PHP's native DOMDocument but provides a more developer-friendly interface for querying (via CSS selectors and XPath) and manipulating elements.

    Key behaviors:

    • Querying: It translates CSS selectors into XPath expressions internally to allow for flexible searching.
    • Node Wrapping: When searching, it can automatically wrap native DOMNode objects into DiDOM Element objects, allowing you to use DiDOM's specialized API on the results.
    • Type Awareness: It maintains state regarding whether the document is html or xml, which affects how content is loaded and exported.
  6. Verify if an element exists

    master

    Use the has() method to check for the existence of elements matching a selector.

    Performance Tip: Instead of calling has() followed by find() (which performs two queries), check the count of the result from find() directly:

    // Faster approach
    if (count($elements = $document->find('.post')) > 0) {
        // code
    }
    if ($document->has('.post')) {
        // code
    }
  7. Work with element attributes

    master

    You can manage attributes on a DiDom\Element using methods or magic properties.

    Setting/Updating Attributes

    • setAttribute($name, $value)
    • attr($name, $value)
    • $element->name = 'value' (Magic __set)

    Getting Attributes

    • getAttribute($name): Returns the value or null if not found.
    • attr($name)
    • $element->name (Magic __get)

    Verifying/Removing Attributes

    • hasAttribute($name): Returns boolean.
    • isset($element->name) (Magic __isset)
    • removeAttribute($name)
    • unset($element->name) (Magic __unset)
  8. Traverse the DOM tree

    master

    DiDOM provides methods to navigate relationships between elements:

    • parent(): Returns the parent Element.
    • previousSibling(): Returns the previous sibling node.
    • nextSibling(): Returns the next sibling node.
    • firstChild(): Returns the first child node (can be text, comment, or element).
    • lastChild(): Returns the last child node.
    • children(): Returns an array of all child nodes.
    • child($index): Returns a specific child node by index.
    • ownerDocument(): Returns the Document instance that owns this element.
  9. Add child elements with appendChild()

    master

    Use appendChild() to add a single Element or an array of Element objects to a parent element.

    $list = new Element('ul');
    $item = new Element('li', 'Item 1');
    
    // Add single element
    $list->appendChild($item);
    
    // Add multiple elements
    $items = [
        new Element('li', 'Item 2'),
        new Element('li', 'Item 3'),
    ];
    $list->appendChild($items);
    $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);
  10. Check if an element matches a selector with matches()

    master

    The matches() method returns true if the element matches the provided CSS selector.

    By default, it checks if the element matches the selector. If you pass true as the second argument, it performs a strict match, meaning the element must match the selector and have no other attributes.

  11. Identify node types with isElementNode, isTextNode, and isCommentNode

    master

    Use these methods to verify the type of a node:

    • isElementNode(): Returns true if the node is a DOMElement.
    • isTextNode(): Returns true if the node is a DOMText.
    • isCommentNode(): Returns true if the node is a DOMComment.
    $element->isElementNode();
    $element->isTextNode();
    $element->isCommentNode();