Skip to content

Latest commit

History

74 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Uss Element

A simple, lightweight, standalone PHP library for programmatically creating and manipulating HTML elements. It simplifies the process of working with HTML structures and DOM elements, offering functionality similar to DOMDocument but with reduced boilerplate and enhanced ease of use.

With UssElement, you can effortlessly create DOM nodes, set attributes, set innerHtml, use querySelector, modify element classlist etc, and generate (or render) HTML strings with ease.

Why Uss Element?

UssElement is designed to simplify and streamline the process of working with HTML elements in PHP. If (like me) you've ever been frustrated by the complexity of PHP's DOMDocument or found yourself writing repetitive, cumbersome code just to manipulate HTML structures, UssElement is the solution you’ve been waiting for.

This standalone library takes care of the heavy lifting, reducing boilerplate code and eliminates the need for complex XPath queries, offering a simple, intuitive API for tasks like creating elements, setting inner HTML, and selecting elements using CSS selectors.

The library is lightweight, fast, and easy to integrate into any project, making it perfect for both small and large-scale applications.

Key Features:

  • Create HTML elements using PHP code.
  • More inspired by Javascript DOM than PHP DOMDocument
  • Set element attributes, such as class names and IDs.
  • Define inner HTML content for elements.
  • Generate or render HTML strings with the NodeInterface::render() method.
  • Boost your productivity by simplifying HTML generation in PHP.
  • Reducing Complexity
  • Providing an Intuitive API
  • Encouraging Dependency-Free Development
  • Efficiency in Common DOM Tasks
  • Flexibility and Extensibility
  • Improving Developer Experience
  • Encoding element to Json format
  • Decoding element from json format

Prerequisite

  • PHP >= 8.2

Installation (Composer)

You can include UssElement library in your project using Composer:

composer require ucscode/uss-element

Getting Started:

  • Instantiate the UssElement class with the desired HTML element type (e.g., NodeNameEnum::NODE_DIV).
  • Use UssElement methods to set attributes and content.
  • Generate HTML strings with NodeInterface::render() for seamless integration into your web pages.

Creating Elements

You can create elements by instantiating the type of node

useUcscode\UssElement\Node\ElementNode;
$element = newElementNode('div');

If you prefer, you can use the NodeNameEnum enum

useUcscode\UssElement\Node\ElementNode;
useUcscode\UssElement\Enums\NodeNameEnum;
$element = newElementNode(NodeNameEnum::NODE_DIV);

You can also create an element and set their attributes at the point of instantiation:

$span = newElementNode('span', [
'id' => 'short-cut',
'class' => 'to set',
'data-what' => 'attributes'
]);

You can use many available methods to manipulate the DOM.

A summary of these methods are provided in the following sections:

$element->appendChild($span);
$element->getNextSibling();
$element->getChild(0)
->setAttribute('data-name', 'Ucscode')
->setAttribute('title', 'Uss Element')
;

Traversing Elements

Use the querySelector() or querySelectorAll() method to select elements based on CSS selectors:

$element->querySelector('.to.set[data-what=attributes]'); // Returns the <span> element

You can also retrieve an element by other methods such as:

  • getElementsByClassName
  • getElementsByTagName
$element->getElementsByClassName('.set'); // Returns the <span> element

Inner HTML

  • You can easily set the inner HTML content of an element using the setInnerHtml() method:
  • You can also get inner HTML of an element using getInnerHTML() method:
$element->setInnerHtml('<p>This is a paragraph inside a div.</p>');

Loading HTML

You can convert an HTML string to NodeList containing all elements using the HtmlLoader class:

useUcscode\UssElement\Parser\Translator\HtmlLoader;
// An example HTML document:$html = <<< 'HERE' <html> <head> <title>TEST</title> </head> <body id='foo'> <h1>Hello World</h1> <p>This is a test of the HTML5 parser.</p> </body> </html>
HERE;
$htmlLoader = newHtmlLoader($html);
$htmlLoader->getNodeList()->count(); // Returns the number of direct nodes (1 in this case)$htmlLoader->getNodeList()->first; // HTML ElementNode

You can also load framents

useUcscode\UssElement\Parser\Translator\HtmlLoader;
$html = <<< 'HERE' <h1>Hi there</h1> <p>Please enter your detail</p> <form name="my-form> <input name="username"/> </form>
HERE;
$htmlLoader = newHtmlLoader($html);
$htmlLoader->getNodeList()->count(); // Returns the number of direct nodes (3 in this case)$htmlLoader->getNodeList()->get(0); // H1 ElementNode$htmlLoader->getNodeList()->get(1); // P ElementNode$htmlLoader->getNodeList()->get(2); // FORM ElementNode

Basic Example

$html = '<div class="container"><p>Hello, world!</p></div>';
$htmlLoader = newHtmlLoader($html);
// Access the root div element$divElement = $htmlLoader->getNodeList()->get(0);
// Set inner HTML of the root element$divElement->setInnerHtml('<i class="fa-icon"></i><h1 class="heading">New Heading</h1><br/>');
// Query the first paragraph within the container$paragraph = $divElement->querySelector('p'); // null$heading = $divElement->querySelector('h1.heading'); // H1 ElementNode// Accessing the number of direct child nodesecho$divElement->getChildNodes()->count(); // 3

Render HTML

You can get or render the ElementNode as HTML using the render() method.

echo$divElement->render();

Output

<divclass="container"><iclass="fa-icon"></i><h1class="heading">New Heading</h1><br/></div>

If you want to indent the rendered output, pass an unsigned integer (initially one) to the render() method

echo$divElement->render(1);

The higher the integer, the more the indentation

Output

<divclass="container"><iclass="fa-icon"></i><h1class="heading">
New Heading
</h1><br/></div>

Element Render Visibility

To keep an element in the DOM tree but exclude it from the rendered output, set its visibility to false.

$divElement->querySelector('.heading')->setVisible(false);
$divElement->render(1);
<divclass="container"><iclass="fa-icon"></i><br/></div>
$divElement->getChildren()->count(); // 3

Setting Void Item

Some HTML elements, like <br> and <img>, do not have closing tags.

The setVoid() method marks an element as void, ensuring that it is rendered without a closing tag. This is especially helpful when defining custom elements.

$element = newElement('x-widget', [
':vue-binder' => 'project'
]);
$element->render(); // <x-widget :vue-binder="project"></x-widget>
$element->setVoid(true);
$element->render(); // <x-widget :vue-binder="project"/>

Encoding and Decoding Nodes

This library provides methods for encoding a node into JSON format and decoding it back to its original structure.
This is useful for transferring nodes between systems or storing them in a format that can be easily reconstructed.

Encoding a Node

To encode a node into JSON format, the toJson() method is used.

$node->toJson(); // Node to JSON Serialization

The toJson() method internally uses an instance of the NodeJsonEncoder, which is the actual encoder responsible for serializing the node.

(newNodeJsonEncoder($node))->encode();

Decoding a Node

To decode a JSON string back into a node, use the NodeJsonDecoder class.

(newNodeJsonDecoder($json))->decode(); // JSON to Node Deserilization

The decoding process restores the full structure of the original node, including its attributes, child nodes, and content.

Normalization

Both the NodeJsonEncoder and NodeJsonDecoder provide a normalize method to convert the input into an array.

(newNodeJsonEncoder($node))->normalize(); // to array
(newNodeJsonDecoder($json))->normalize(); // to array

NodeInterface methods

MethodDescriptionReturns
getNodeNameReturn the name of the current nodestring
getNodeTypeReturn the node identifierinteger
setVisibleSet the visibility state of a node when renderedstatic
isVisibleVerify the visibility state of a node when renderedboolean
renderConvert the node to string (OuterHTML)string
getParentElementReturns an Element that is the parent of the current nodeElementInterface|null
getParentNodeReturns a Node that is the parent of the current nodeNodeInterface|null
getChildNodesReturns a NodeList containing all the children of the current nodeNodeList
clearChildNodesRemove all the child Nodes from the current elementstatic
appendChildAdds the specified Node argument as the last child to the current nodestatic
prependChildAdds the specified Node argument as the first child to the current nodestatic
getFirstChildReturns a Node representing the last direct child node of the current nodeNodeInterface|null
getLastChildReturns a Node representing the last direct child node of the nodeNodeInterface|null
getNextSiblingReturns a Node representing the next node in the treeNodeInterface|null
getPreviousSiblingReturns a Node representing the previous node in the treeNodeInterface|null
insertBeforeInserts a Node before the reference node as a child of a specified parent nodestatic
insertAfterInserts a Node after the reference node as a child of a specified parent nodestatic
insertAdjacentNodeInserts a Node at a specific position relative to other child nodesstatic
hasChildVerify that a node has the provided child nodeboolean
getChildGet a child node from the NodelistNodeInterface|null
removeChildRemoves a child node from the current elementstatic
replaceChildReplaces one child Node of the current one with the second one given in parameterstatic
cloneNodeClone a Node, and optionally, all of its contentsNodeInterface
sortChildNodesReorder the child nodes of a specified parent nodestatic
moveBeforeMove the current node before a sibling node within the same parent nodestatic
moveAfterMove the current node after a sibling node within the same parent nodestatic
moveToFirstMove the current node to the first position of its relative sibling nodesstatic
moveToLastMove the current node to the last position of its relative sibling nodesstatic
moveToIndexMove the current node to a specific position within its sibling nodesstatic
toJson Converts the node and its descendants into a JSON-encoded stringstring

ElementInterface methods

Includes:

MethodDescriptionReturns
getTagNameReturn the tag name of the current elementstring
setInnerHtmlSet the inner HTML of the elementstatic
getInnerHtmlGet the inner HTML of the elementstring
setVoidSet whether the element is void (no closing tag)static
isVoidVerify if the element is void, meaning it has no closing tagboolean
getOpenTagGet the opening tag of the elementstring
getCloseTagGet the closing tag of the element (if any)string|null
getChildrenGet a collection of the element's childrenElementList
getAttributeGet the value of a specific attribute by namestring|null
getAttributesGet a collection of all attributes of the elementAttributes
getAttributeNamesGet a list of all attribute names of the elementarray
hasAttributeCheck if the element has a specific attributeboolean
hasAttributesCheck if the element has any attributesboolean
setAttributeSet the value of a specific attributestatic
removeAttributeRemove a specific attribute from the elementstatic
querySelectorFind and return the first matching element by the given CSS selectorElementInterface|null
querySelectorAllFind and return all matching elements by the given CSS selectorElementList
getClassListGet a collection of classes of the elementClassList
matchesCheck if the current element matches the given CSS selectorboolean
getElementsByClassNameGet all elements with the specified class nameElementList
getElementsByTagNameGet all elements with the specified tag nameElementList

TextNode methods

Includes:

MethodDescriptionReturns
getDataGet the text datastring
lengthThe length of the text datainteger
isContentWhiteSpaceCheck if the content of the text node is empty or contains only whitespaceboolean

Collection Objects

PHP ClassDescription
AttributesManages attributes of an element.
ClassListHandles class names for an element.
ElementListA collection of ElementInterface types.
NodeListA collection of any node types.

Node Objects

PHP ClassDescription
CommentNodeRepresents HTML comments.
DocumentTypeNodeRepresents the <!DOCTYPE> declaration.
ElementNodeRepresents HTML elements.
TextNodeRepresents textual content.

Parser Objects

PHP ClassDescription
HtmlLoaderParses an HTML string into nodes.
MatcherMatches nodes against CSS selectors.
TokenizerBreaks down CSS selectors into tokens.
TransformerEncodes and decodes CSS selectors.
NodeSelectorFinds descendants matching CSS selectors.
NodeJsonEncoderEncodes a node and its descendants into JSON format
NodeJsonDecoderDecodes a node JSON back into a node instance.

Providing Support For:

  • Combinators: Use of combinator such as >, +, ~, $ are captured but not yet supported

Contributing

Feel free to open issues or submit pull requests. We welcome contributions to improve the library.

How to Contribute

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature-xyz).
  3. Commit your changes (git commit -am 'Add feature xyz').
  4. Push to the branch (git push origin feature-xyz).
  5. Create a new pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A lightweight standalone PHP library to programmatically generate and manipulate HTML elements

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages