Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete every element of specific type in php?

Hey so i have a use of a php function that would delete every element of specific type in php. More specifically i want to delete all the labels on my website, e.g:

DOMDocument::deleteAllElementsOfType("label");

Any help is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A couple of ways:

With XPath:

<?php
$dom = new DOMDocument();

$dom->loadHtml('
<form>
    <label>a</label>
    <input />
    <label>b</label>
    <input />
    <label>c</label>
    <input />
</form>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);

foreach ($xpath->query("//label") as $label) $label->parentNode->removeChild($label);

echo $dom->saveHTML();

Result

<form>
    
    <input>
    
    <input>
    
    <input>
</form>

With getElementsByTagName

Due to it being a live document you convert the iterator to an array with iterator_to_array

$dom = new DOMDocument();

$dom->loadHtml('
<form>
    <label>a</label>
    <input />
    <label>b</label>
    <input />
    <label>c</label>
    <input />
</form>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

foreach (iterator_to_array($dom->getElementsByTagName('label')) as $label) $label->parentNode->removeChild($label);

echo $dom->saveHTML();

Result

<form>
    
    <input>
    
    <input>
    
    <input>
</form>

See it online: https://3v4l.org/WJpqk

You could extend DOMDocument if you want to add your own methods

<?php
class Document extends \DOMDocument {
    function __construct(string $version = "1.0", string $encoding = "") {
        parent::__construct($version, $encoding);
    }
    
    public function deleteAllElementsOfType(string $type) {
        foreach (iterator_to_array($this->getElementsByTagName($type)) as $item) $item->parentNode->removeChild($item);
    }
}

$dom = new Document();

$dom->loadHtml('
<form>
    <label>a</label>
    <input />
    <label>b</label>
    <input />
    <label>c</label>
    <input />
</form>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$dom->deleteAllElementsOfType('label');

echo $dom->saveHTML();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading