Skip to content
Advertisement

How to delete every element of specific type in php? [closed]

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.

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement