'php DOMdocument how to select multiple tag elements?
I have the following code below
$Dom = new DOMDocument;
@$Dom->loadHTML("<?xml version='1.0' encoding='UTF-8'?><body>$body</body>");
$links = $Dom->getElementsByTagName('a');
$arr = array();
foreach ($links as $link) {
if ($link->attributes[0]->name == 'href' && $link->attributes[0]->value != '#') {
$link->attributes[0]->value = 'changed.com';
}
}
i want to also add the button tag something like this $Dom->getElementsByTagName('a,button');
Solution 1:[1]
You can use DOMXPath::query() or extends DOMElement and register by DOMDocument::registerNodeClass()
Solution 2:[2]
You can use a multiple selector using XPath : $xpath->query('//a | //button').
// HTML sample
$body = '<p><a href="#">link</a><a href="#">another</a><button>button</button><i>some text</i></p>';
// Load and query
$dom = new DOMDocument;
@$dom->loadHTML("<?xml version='1.0' encoding='UTF-8'?><body>$body</body>");
$xpath = new DOMXPath($dom);
$nodelist = $xpath->query('//a | //button');
// Display information
echo "Length is : " . $nodelist->length, PHP_EOL;
foreach ($nodelist as $index => $node) {
echo "- Node $index is $node->nodeName" . PHP_EOL;
}
Output:
Length is : 3
Node 0 is a
Node 1 is a
Node 2 is button
See also a live demo (3v4l.org).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Syscall |
