SimpleDom
, (*1)
SimpleDom adds simple class manipulation to DOMDocuments and DOMElements., (*2)
Requirements
Installation
SimpleDom can be installed by using Composer. Simply run:, (*3)
composer require devvoh/simpledom, (*4)
Usage
SimpleDom can be considered a facade adapter for the built-in DOMDocument and DOMElement classes. As such, you can use them anywhere you currently use those., (*5)
Creating a new instance is done with an extra step, however:, (*6)
$domDocument = new \DOMDocument();
$domDocument->loadHTML($htmlString);
$document = \SimpleDom\Document::fromDOMDocument($domDocument);
To then get all elements with the class "header":, (*7)
$elements = $document->getElementsByClassName("header");
And you'll get an array of \SimpleDom\Element items. SimpleDom also overwrites the following DOMDocument methods: getElementsByTagName(), getElementById() and createElement()., (*8)
Normally the getElement methods would return a DOMNodeList but SimpleDom returns an array of elements instead., (*9)
It's also possible to get elements which have multiple classes., (*10)
$elements = $document->getElementsByClassNames(["header", "sub"]);
Which will only return items that have both the "header" and "sub" class. The order of which is not important., (*11)
To get the DOMDocument back so you can save the HTML, simply do this:, (*12)
$domDocument = $document->getDOMDocument();
echo $domDocument->saveHTML();
SimpleDom Element instances have some added features as well., (*13)
$element = $document->createElement("span", "this is a span!");
$element->addClass("blue");
The above code will result in the following html: <span class="blue">this is a span!</span>, (*14)
The following methods are available to work with classes and Elements:
- getClasses(): array
- setClasses(array): Element
- hasClass(string): bool
- hasClasses(array): bool
- addClass(string): Element
- addClasses(array): Element
- removeClass(string): Element
- removeClasses(array): Element
- toggleClass(string): Element
- toggleClasses(array): Element
- clearClasses(): Element, (*15)
All questions can be asked through github. Just create an issue and I'll get back with an answer as soon as possible., (*16)
License
Devvoh SimpleDom is open-sourced software licensed under the MIT license., (*17)