PHP code example of manychois / simdom

1. Go to this page and download the library: Download manychois/simdom library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

manychois / simdom example snippets


use Manychois\Simdom\HtmlParser;

$parser = new HtmlParser();
$doc = $parser->parseDocument('<!DOCTYPE html><html><body><p>Hello, world!</p></body></html>');
// $doc is an instance of \Manychois\Simdom\Document

use Manychois\Simdom\Document;
use Manychois\Simdom\Element;

// Create documents
$doc = Document::create();

// Create elements
$div = Element::create('div');
$div->setAttr('class', 'container');
$div->id = 'main-content';

// Access document parts
$html = $doc->documentElement; // The <html> element
$head = $doc->head;           // The <head> element
$body = $doc->body;           // The <body> element

// Navigate the tree
$element = $body->firstElementChild;
$nextElement = $element->nextElementSibling;
$parent = $element->parent;

// Child node access
foreach ($body->childNodes as $node) {
    echo get_class($node) . "\n";
}

// Element-only access
foreach ($body->children as $element) {
    echo $element->name . "\n";
}

// Append nodes
$body->append($div, $text);
$body->appendChild($comment);

// Prepend nodes
$body->prepend(Text::create('First text'));

// Insert before/after
$div->before(Comment::create('Before div'));
$div->after(Text::create('After div'));

// Replace nodes
$div->replaceWith(Element::create('section'));

// Remove nodes
$div->remove();

$element = Element::create('input');
// Set attributes
$element->setAttr('type', 'text');
// Get attributes
$type = $element->getAttr('type'); // 'text'
$missing = $element->getAttr('missing'); // null
// Check existence
$hasType = $element->hasAttr('type'); // true
// Remove attributes
$element->removeAttr('name');
// Get all attributes
$attrs = $element->attrs(); // ['type' => 'text']

// Depth-first search
$found = $doc->dfs(fn($node) => $node instanceof Element && $node->id === 'target');

// Breadth-first search
$found = $doc->bfs(fn($node) => $node instanceof Element && $node->name === 'button');

// Find the first form
$form = $doc->querySelector('form');

// Iterate through all descendants
foreach ($doc->descendants() as $node) {
    if ($node instanceof Text) {
        echo $node->data . "\n";
    }
}

// Convert to string representation
$html = (string) $doc;
// or using the __toString() method
$html = $element->__toString();