php文档如何选择多个标记元素



下面有以下代码

$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';
}
}

我还想添加类似于$Dom->getElementsByTagName('a,button');的按钮标签

您可以使用DOMXPath::query()或扩展DOMElement并通过DOMDocument::registerNodeClass()注册

您可以使用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;
}

输出:

Length is : 3
Node 0 is a
Node 1 is a
Node 2 is button

另请参阅现场演示(3v4l.org(。

最新更新